package com.sicpa.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sicpa.common.annotation.Excel;
import com.sicpa.common.annotation.ParamNotNull;
import com.sicpa.common.constant.DataInPathConstants;
import com.sicpa.common.constant.HttpStatus;
import com.sicpa.common.core.domain.AjaxResult;
import com.sicpa.common.core.domain.entity.*;
import com.sicpa.common.core.domain.model.LoginUser;
import com.sicpa.common.core.page.PageDomain;
import com.sicpa.common.core.page.TableDataInfo;
import com.sicpa.common.core.page.TableSupport;
import com.sicpa.common.core.redis.RedisCache;
import com.sicpa.common.core.text.Convert;
import com.sicpa.common.enums.*;
import com.sicpa.common.ftp.FtpFactory;
import com.sicpa.common.utils.*;
import com.sicpa.common.utils.bean.BeanUtils;
import com.sicpa.common.utils.html2pdf.PDFUtil;
import com.sicpa.common.utils.html2pdf.PdfDocumentGenerator;
import com.sicpa.common.utils.sql.SqlUtil;
import com.sicpa.system.domain.SysConfig;
import com.sicpa.system.mapper.*;
import com.sicpa.system.service.*;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.sicpa.common.utils.DateUtils.YYYY_MM_DD_HH_MM_SS;

/**
 * AssuranceBusinessDataReportServiceImpl
 *
 * @author lwf
 */
@Service
public class AssuranceBusinessDataReportServiceImpl implements IAssuranceBusinessDataReportService {

    private static final Logger log = LoggerFactory.getLogger(AssuranceBusinessDataReportServiceImpl.class);

    private AssuranceBusinessDataReportMapper assuranceBusinessDataReportMapper;

    private AssuranceBusinessDataReportTempMapper assuranceBusinessDataReportTempMapper;

    private AssuranceBusinessDataRegisterSignatureMapper assuranceBusinessDataRegisterSignatureMapper;

    private IAntiCounterfeitingProcessRecordService iAntiCounterfeitingProcessRecord;

    private ISysConfigService iSysConfigService;

    private ISysNoticeService iSysNoticeService;

    private AntiCounterfeitingRegisteredOfficeMapper antiCounterfeitingRegisteredOfficeMapper;

    private SysUserMapper sysUserMapper;

    private SysDictDataMapper sysDictDataMapper;

    private ICheckUserPowerService iCheckUserPowerService;

    private AntiCounterfeitingProcessRecordImpl antiCounterfeitingProcessRecordImpl;

    private AntiCounterfeitingProcessRecordMapper antiCounterfeitingProcessRecordMapper;

    private RedisCache redisCache;

    private TemplateEngine templateEngine;

    private PdfDocumentGenerator pdfDocumentGenerator;
    private ISysUserService userService;
    private FtpFactory ftpFactory;

    private AntiCounterfeitingUpdateContractMapper antiCounterfeitingUpdateContractMapper;

    private String dateType = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|" +
            "((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|" +
            "((0[48]|[2468][048]|[3579][26])00))-02-29)$";
    //二维码路径
    @Value("${qRCode.url}")
    private String qRCodeUrl;

    //生成报告封面的thymeleaf模版，在 resources/templates 下
    @Value("${report.templateName}")
    private String reportTemplateName;

    //报告封面模版，事务所名称 > 38 换行 ，封面名称 > 38 换行，通讯地址 > 38 换行
    @Value("${report.fireNameLength}")
    private Integer fireNameLength;

    //报告封面模版，报告文号 > 30 换行
    @Value("${report.reportNoLength}")
    private Integer reportNoLength;

    //报告封面模版，报告文号 > 30 换行
    @Value("${report.outFilePath}")
    private String outFilePath;

    @Autowired
    public AssuranceBusinessDataReportServiceImpl(AssuranceBusinessDataReportMapper assuranceBusinessDataReportMapper, AssuranceBusinessDataRegisterSignatureMapper assuranceBusinessDataRegisterSignatureMapper, IAntiCounterfeitingProcessRecordService iAntiCounterfeitingProcessRecord, ISysConfigService iSysConfigService, ISysNoticeService iSysNoticeService
            , AntiCounterfeitingRegisteredOfficeMapper antiCounterfeitingRegisteredOfficeMapper, SysUserMapper sysUserMapper, SysDictDataMapper sysDictDataMapper, AssuranceBusinessDataReportTempMapper assuranceBusinessDataReportTempMapper, ICheckUserPowerService iCheckUserPowerService, AntiCounterfeitingProcessRecordImpl antiCounterfeitingProcessRecordImpl,
                                                  RedisCache redisCache, AntiCounterfeitingProcessRecordMapper antiCounterfeitingProcessRecordMapper, TemplateEngine templateEngine, PdfDocumentGenerator pdfDocumentGenerator
            , FtpFactory ftpFactory, ISysUserService userService, AntiCounterfeitingUpdateContractMapper antiCounterfeitingUpdateContractMapper) {
        this.assuranceBusinessDataReportMapper = assuranceBusinessDataReportMapper;
        this.assuranceBusinessDataRegisterSignatureMapper = assuranceBusinessDataRegisterSignatureMapper;
        this.iAntiCounterfeitingProcessRecord = iAntiCounterfeitingProcessRecord;
        this.iSysConfigService = iSysConfigService;
        this.iSysNoticeService = iSysNoticeService;
        this.antiCounterfeitingRegisteredOfficeMapper = antiCounterfeitingRegisteredOfficeMapper;
        this.sysUserMapper = sysUserMapper;
        this.sysDictDataMapper = sysDictDataMapper;
        this.assuranceBusinessDataReportTempMapper = assuranceBusinessDataReportTempMapper;
        this.iCheckUserPowerService = iCheckUserPowerService;
        this.antiCounterfeitingProcessRecordImpl = antiCounterfeitingProcessRecordImpl;
        this.redisCache = redisCache;
        this.antiCounterfeitingProcessRecordMapper = antiCounterfeitingProcessRecordMapper;
        this.templateEngine = templateEngine;
        this.pdfDocumentGenerator = pdfDocumentGenerator;
        this.ftpFactory = ftpFactory;
        this.userService = userService;
        this.antiCounterfeitingUpdateContractMapper = antiCounterfeitingUpdateContractMapper;
    }

    //路径1导入时的流程节点
    private static String[] stageDetail = new String[]{"导入前准备", "数据必填字段校验", "类型及范围校验", "事务所名称校验", "报备编码过滤", "数据入库处理", "导入完成"};

    /**
     * 鉴证业务数据保存草稿
     *
     * @param report
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveDraft(AssuranceBusinessDataReport report) {
        report.setStatus(0);
        report.setDataStatus("3");
        report.setContrastStatus("0");
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Integer isOfficeAccount = sysUser.getIsOfficeAccount();
        if (isOfficeAccount != null && isOfficeAccount == 1) {
            Long officeId = sysUser.getOfficeId();
            AntiCounterfeitingRegisteredOffice office = antiCounterfeitingRegisteredOfficeMapper.selectByOfficeId(officeId);
            report.setFirmName(office.getFirmName());
            report.setOfficeId(officeId);
            report.setAdministrativeDivision(office.getProvince());
            report.setHasSecurities(office.getHaveSecuritiesQualification());
        }
        report.setCreateBy(sysUser.getUserId().toString());
        Long businessId = report.getBusinessId();
        if (businessId != null && businessId > 0L) {
            assuranceBusinessDataReportMapper.updateReportNoCount(report);
        } else {
            assuranceBusinessDataReportMapper.insertReport(report);
        }
        assuranceBusinessDataRegisterSignatureMapper.deleteByBusinessId(report.getBusinessId());
        addSignatureRegistered(report);
        return report.getBusinessId();
    }

    /**
     * 新增鉴证业务报告
     *
     * @param assuranceBusinessDataReport
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insertReport(AssuranceBusinessDataReport assuranceBusinessDataReport) {
        Set<String> permissionSet = SecurityUtils.getLoginUser().getPermissions();
        if (permissionSet.contains(PerssionCheckEnum.ASSURANCE_NEED_REVIEW.getPerssionKey())) {
            return insertReport(assuranceBusinessDataReport, "6");
        }
        return insertReport(assuranceBusinessDataReport, null);
    }

    /**
     * 对比修改鉴证业务报告
     *
     * @param assuranceBusinessDataReport
     * @return
     */
    @Override
    public AjaxResult compareEdit(AssuranceBusinessDataReport assuranceBusinessDataReport) {
        Long businessId = assuranceBusinessDataReport.getBusinessId();
        String json = assuranceBusinessDataReportTempMapper.selectByBusinessId(businessId);
        if (StringUtils.isNotEmpty(json)) {
           /* AssuranceBusinessDataReport finaceBusinessDataReport = JSON.parseObject(json, AssuranceBusinessDataReport.class);
            finaceBusinessDataReport.setBusinessId(businessId);
            finaceBusinessDataReport.setDataStatus("3");
            finaceBusinessDataReport.setContrastStatus("1");
            finaceBusinessDataReport.setDataMatchingResults("一致");
*/
            Integer matchCount = matchConditionalData(assuranceBusinessDataReport.getAuditYear(), assuranceBusinessDataReport.getReportType(), assuranceBusinessDataReport.getCustomerName(), assuranceBusinessDataReport.getCustomerBusinessLicense(), assuranceBusinessDataReport.getBusinessId());
            if (matchCount != null && matchCount > 0) {
                assuranceBusinessDataReport.setDataStatus("2");
                //2020/11/10 根据2020/11/09会议调整 修改数据异常后流程，只改变状态，流程照常进行，生成防伪编码
                   /* AssuranceBusinessDataReport dataReport = importSaveAssuranceBusinessDataReport(assuranceBusinessDataReport);
                    dataExceptionNotify("鉴证业务数据录入异常", "编号：" + dataReport.getBusinessId() + "的业务数据录入异常!", dataReport.getBusinessId());
                    return AjaxResult.success("业务数据保存成功,但该数据异常!");*/
            } else {
                assuranceBusinessDataReport.setDataStatus("3");
            }
            //assuranceBusinessDataReport.setDataStatus("3");
            assuranceBusinessDataReport.setContrastStatus("1");
            assuranceBusinessDataReport.setDataMatchingResults("一致");
            importSaveAssuranceBusinessDataReport(assuranceBusinessDataReport);
        } else {
            return AjaxResult.error("数据不存在!");
        }
        return AjaxResult.success(businessId);
    }

    /**
     * 新增鉴证业务报告
     *
     * @param assuranceBusinessDataReport
     * @param dataStatus
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult insertReport(AssuranceBusinessDataReport assuranceBusinessDataReport, String dataStatus) {
        String reportNo = assuranceBusinessDataReport.getReportNo();
        if (StringUtils.isNotEmpty(reportNo)) {
            String clearReportNo = StringUtils.removeSign(reportNo);
            assuranceBusinessDataReport.setReportNoClean(clearReportNo);
            Integer checkCount = reportNoRepeatCheck(reportNo, assuranceBusinessDataReport.getBusinessId());
            if (checkCount != null && checkCount > 0) {
                return AjaxResult.error(AbnormalInfoEnum.REPORT_NO_REPEAT.getMsg());
            } else {
                Integer matchCount = matchConditionalData(assuranceBusinessDataReport.getAuditYear(), assuranceBusinessDataReport.getReportType(), assuranceBusinessDataReport.getCustomerName(), assuranceBusinessDataReport.getCustomerBusinessLicense(), assuranceBusinessDataReport.getBusinessId());
                if (matchCount != null && matchCount > 0) {
                    assuranceBusinessDataReport.setDataStatus("2");
                    //2020/11/10 根据2020/11/09会议调整 修改数据异常后流程，只改变状态，流程照常进行，生成防伪编码
                   /* AssuranceBusinessDataReport dataReport = importSaveAssuranceBusinessDataReport(assuranceBusinessDataReport);
                    dataExceptionNotify("鉴证业务数据录入异常", "编号：" + dataReport.getBusinessId() + "的业务数据录入异常!", dataReport.getBusinessId());
                    return AjaxResult.success("业务数据保存成功,但该数据异常!");*/
                } else {
                    assuranceBusinessDataReport.setDataStatus("3");
                }
            }
        } else {
            return AjaxResult.error(AbnormalInfoEnum.REPORT_NO_NON_EXISTENT.getMsg());
        }
        if (StringUtils.equals(dataStatus, "6")) {
            assuranceBusinessDataReport.setDataStatus(dataStatus);
            importSaveAssuranceBusinessDataReport(assuranceBusinessDataReport);
        } else {
            //判断是否是编辑页面
            if (assuranceBusinessDataReport.getBusinessId() != null) {
                AssuranceBusinessDataReport item = assuranceBusinessDataReportMapper.selectReportByBusinessIdFu(assuranceBusinessDataReport.getBusinessId());
                if (0 == item.getStatus()) {
                    assuranceBusinessDataReport.setContrastStatus("0");
                    generateAntiCode(assuranceBusinessDataReport);
                } else {
                    if ("1".equals(item.getContrastStatus())) {
                        assuranceBusinessDataReport.setDataStatus("9");
                    } else if ("6".equals(item.getDataStatus()) || "7".equals(item.getDataStatus()) || "8".equals(item.getDataStatus())) {
                        assuranceBusinessDataReport.setDataStatus("6");
                    }
                    /* assuranceBusinessDataReport.setContrastStatus("0");*/
                    //编辑不改变防伪编码，二维码
                    importSaveAssuranceBusinessDataReport(assuranceBusinessDataReport);
                }

            } else {
                assuranceBusinessDataReport.setContrastStatus("0");
                generateAntiCode(assuranceBusinessDataReport);
            }
        }
        return AjaxResult.success("业务数据保存成功");
    }

    /**
     * 根据鉴证业务数据报告id获取详细信息
     *
     * @param businessId
     * @return
     */
    @Override
    public AssuranceBusinessDataReport selectReportByBusinessId(Long businessId) {
        AssuranceBusinessDataReport assuranceBusinessDataReport = assuranceBusinessDataReportMapper.selectReportByBusinessId(businessId);
        if (assuranceBusinessDataReport == null) {
            assuranceBusinessDataReport = assuranceBusinessDataReportMapper.selectReportByBusinessIdFu(businessId);
        }
        String antiCounterfeitingCoding = assuranceBusinessDataReport.getAntiCounterfeitingCoding();
        if (antiCounterfeitingCoding != null) {
            assuranceBusinessDataReport.setqRCode(generateQrCode(assuranceBusinessDataReport));
        }
        Long officeId = assuranceBusinessDataReport.getOfficeId();
        AntiCounterfeitingRegisteredOffice office = antiCounterfeitingRegisteredOfficeMapper.selectByOfficeId(officeId);
        if (office != null) {
            assuranceBusinessDataReport.setOffice(office);
        }
        return assuranceBusinessDataReport;
    }

    /**
     * 鉴证业务历史数据导出
     *
     * @param businessId
     * @return
     */
    @Override
    public List<AssuranceBusinessDataReport> importEditHistory(Long businessId) {
        List<AssuranceBusinessDataReport> result = new ArrayList<>();
        List<AssuranceBusinessDataReportTemp> list = assuranceBusinessDataReportTempMapper.selectEditHistoryByBusinessId(businessId);
        if (list != null && list.size() > 0) {
            list.forEach(item -> {
                String json = item.getJson();
                result.add(JSON.parseObject(json, AssuranceBusinessDataReport.class));
            });
        }
        return result;
    }

    /**
     * 组长查询
     *
     * @param assuranceBusinessDataReport
     * @param list
     * @return
     */
    @Override
    public TableDataInfo zeSelect(AssuranceBusinessDataReport assuranceBusinessDataReport, List<String> list) {
        String idStr = assuranceBusinessDataReport.getIds();
        if (idStr != null && idStr != "") {
            String[] ids = idStr.split(",");
            assuranceBusinessDataReport.setIdList(ids);
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        List<AssuranceBusinessDataReport> reportList = new ArrayList<>();
        if (Optional.ofNullable(list).isPresent() && list.size() > 0) {
            assuranceBusinessDataReport.setOfficeIdList(list);
            startPage();
            if (StringUtils.isNotEmpty(assuranceBusinessDataReport.getSignCertificateNo1()) || StringUtils.isNotEmpty(assuranceBusinessDataReport.getSignerName1())) {
                reportList = assuranceBusinessDataReportMapper.selectReportByOfficeIdAndRegistered(assuranceBusinessDataReport);
            } else {
                reportList = assuranceBusinessDataReportMapper.selectReportByOfficeIdList(assuranceBusinessDataReport);
            }
            rspData.setTotal(new PageInfo(reportList).getTotal());
            changeRegisterList(assuranceBusinessDataReport, reportList);
            List<String> ids = new ArrayList<>();
            for (int i = 0; i < reportList.size(); i++) {
                ids.add(reportList.get(i).getBusinessId().toString());
            }
            if (ids.size() > 0) {
                assuranceBusinessDataReport.setIdList(ids.toArray(new String[ids.size()]));
                reportList = assuranceBusinessDataReportMapper.selectReportAndRegisteres(assuranceBusinessDataReport);
            }
        }
        // genQrCode(reportList);
        rspData.setRows(reportList);
        return rspData;
    }

    /**
     * 获取用户事务所
     *
     * @return
     */
    @Override
    public AntiCounterfeitingRegisteredOffice getOfficeByNum() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        return antiCounterfeitingRegisteredOfficeMapper.selectByOfficeId(user.getOfficeId());
    }

    /**
     * 普通查询
     *
     * @param assuranceBusinessDataReport
     * @return
     */
    @Override
    public TableDataInfo puSelect(AssuranceBusinessDataReport assuranceBusinessDataReport) {
        String idStr = assuranceBusinessDataReport.getIds();
        if (idStr != null && idStr != "") {
            String[] ids = idStr.split(",");
            assuranceBusinessDataReport.setIdList(ids);
        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");

        List<AssuranceBusinessDataReport> reportList = new ArrayList<>();
        startPage();
        if (StringUtils.isNotEmpty(assuranceBusinessDataReport.getSignCertificateNo1()) || StringUtils.isNotEmpty(assuranceBusinessDataReport.getSignerName1())) {
            reportList = assuranceBusinessDataReportMapper.selectReportByOfficeIdAndRegistered(assuranceBusinessDataReport);
        } else {
            reportList = assuranceBusinessDataReportMapper.selectReportByOfficeId(assuranceBusinessDataReport);
        }
        rspData.setTotal(new PageInfo(reportList).getTotal());

        List<String> ids = new ArrayList<>();
        for (int i = 0; i < reportList.size(); i++) {
            ids.add(reportList.get(i).getBusinessId().toString());
        }
        if (ids.size() > 0) {
            assuranceBusinessDataReport.setIdList(ids.toArray(new String[ids.size()]));
            reportList = assuranceBusinessDataReportMapper.selectReportAndRegisteres(assuranceBusinessDataReport);
        }
        changeRegisterList(assuranceBusinessDataReport, reportList);
        //生成二维码 -- 查询list列表时不用
        //  genQrCode(reportList);
        rspData.setRows(reportList);
        return rspData;
    }

    /**
     * 上注协和财政
     *
     * @param assuranceBusinessDataReport
     * @param isFin
     * @return
     */
    @Override
    public TableDataInfo scipaSelect(AssuranceBusinessDataReport assuranceBusinessDataReport, boolean isFin) {
        String idStr = assuranceBusinessDataReport.getIds();
        if (idStr != null && idStr != "") {
            String[] ids = idStr.split(",");
            assuranceBusinessDataReport.setIdList(ids);
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        List<AssuranceBusinessDataReport> reportList = new ArrayList<>();
        startPage();
        if (StringUtils.isNotEmpty(assuranceBusinessDataReport.getSignCertificateNo1()) || StringUtils.isNotEmpty(assuranceBusinessDataReport.getSignerName1())) {
            reportList = assuranceBusinessDataReportMapper.selectReportByOfficeIdAndRegistered(assuranceBusinessDataReport);
        } else {
            reportList = assuranceBusinessDataReportMapper.selectReportList(assuranceBusinessDataReport);
        }
        rspData.setTotal(new PageInfo(reportList).getTotal());

        List<String> ids = new ArrayList<>();
        for (int i = 0; i < reportList.size(); i++) {
            ids.add(reportList.get(i).getBusinessId().toString());
        }
        if (ids.size() > 0) {
            assuranceBusinessDataReport.setIdList(ids.toArray(new String[ids.size()]));
            reportList = assuranceBusinessDataReportMapper.selectReportAndRegisteres(assuranceBusinessDataReport);
        }
        changeRegisterList(assuranceBusinessDataReport, reportList);
        //  genQrCode(reportList);
        rspData.setRows(reportList);
        return rspData;
    }

    /**
     * 把注册师list转为报告的注册师1234
     *
     * @param assuranceBusinessDataReport  判断查询条件是否有注册师，补全注册师
     * @param assuranceBusinessDataReports
     */
    private void changeRegisterList(AssuranceBusinessDataReport assuranceBusinessDataReport, List<AssuranceBusinessDataReport> assuranceBusinessDataReports) {
        for (int y = 0; y < assuranceBusinessDataReports.size(); y++) {
            AssuranceBusinessDataReport item = assuranceBusinessDataReports.get(y);
            List<AssuranceBusinessDataRegisterSignature> registerList = new ArrayList<>();
            registerList = item.getAssuranceBusinessDataRegisterSignatures();
            if (registerList.size() > 1) {
                if (registerList.size() > 0) {
                    item.setSignCertificateNo1(registerList.get(0).getRegistrationCertificateNo());
                    item.setSignerName1(registerList.get(0).getRegistrantName());
                }
                if (registerList.size() > 1) {
                    item.setSignCertificateNo2(registerList.get(1).getRegistrationCertificateNo());
                    item.setSignerName2(registerList.get(1).getRegistrantName());
                }
                if (registerList.size() > 2) {
                    item.setSignCertificateNo3(registerList.get(2).getRegistrationCertificateNo());
                    item.setSignerName3(registerList.get(2).getRegistrantName());
                }
                if (registerList.size() > 3) {
                    item.setSignCertificateNo4(registerList.get(3).getRegistrationCertificateNo());
                    item.setSignerName4(registerList.get(3).getRegistrantName());
                }
            } else {
                if (registerList.size() == 1 && registerList.get(0).getRegistrationCertificateNo() != null && registerList.get(0).getRegistrantName() != null) {
                    item.setSignCertificateNo1(registerList.get(0).getRegistrationCertificateNo());
                    item.setSignerName1(registerList.get(0).getRegistrantName());
                } else {
                    item.setAssuranceBusinessDataRegisterSignatures(new ArrayList<AssuranceBusinessDataRegisterSignature>());
                }

            }
        }
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 生成二维码
     *
     * @param assuranceBusinessDataReports
     * @return
     */
    public List<AssuranceBusinessDataReport> genQrCode(List<AssuranceBusinessDataReport> assuranceBusinessDataReports) {
        for (AssuranceBusinessDataReport report : assuranceBusinessDataReports) {
            byte[] qrCode = generateQrCode(report);
            if (qrCode != null) {
                report.setqRCode(qrCode);
            }
        }
        return assuranceBusinessDataReports;
    }

    /**
     * 生成
     *
     * @param report
     * @return
     */
    private byte[] generateQrCode(AssuranceBusinessDataReport report) {
        String dataStatus = report.getDataStatus();
        if (StringUtils.isNotEmpty(report.getAntiCounterfeitingCoding()) && !StringUtils.equals(dataStatus, "4")) {
            //生成二维码路径
            String url = qRCodeUrl + report.getAntiCounterfeitingCoding();
            try {
                return QrCodeGenerateUtil.getQRCodeImage(url, 400, 400);
            } catch (Exception e) {
                log.error("生成二维码报错" + url);
            }
        }
        return null;
    }

    /**
     * 删除鉴证业务数据报告
     *
     * @param businessIdS
     * @return
     */
    @Override
    public int deleteDeptByBusinessId(String businessIdS) {
        return assuranceBusinessDataReportMapper.deleteDeptByBusinessId(Convert.toStrArray(businessIdS));
    }

    /**
     * 获取鉴证业务数据报告草稿
     *
     * @param assuranceBusinessDataReport
     * @return
     */
    @Override
    public List<AssuranceBusinessDataReport> selectReportListDraft(AssuranceBusinessDataReport assuranceBusinessDataReport) {
        //获取登录用户
        SysUser user = SecurityUtils.getLoginUser().getUser();
        assuranceBusinessDataReport.setCreateBy(user.getUserId().toString());
        return assuranceBusinessDataReportMapper.selectReportDraftList(assuranceBusinessDataReport);
    }

    /**
     * 预上传字段配置
     *
     * @param configJson
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void preUploadConfig(String configJson) {
        SysConfig sysConfig = iSysConfigService.selectConfigByConfigKey(ConfigKeyEnum.PRE_UPLOAD_KEY.getValue());
        sysConfig.setConfigValue(configJson);
        iSysConfigService.updateConfig(sysConfig);
    }

    /**
     * 申请财政退回
     *
     * @param businessId
     * @param reason
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int back(Long businessId, String reason) {
        AssuranceBusinessDataReport assuranceBusinessDataReport = assuranceBusinessDataReportMapper.selectReportByBusinessId(businessId);
        String contrastStatus = assuranceBusinessDataReport.getContrastStatus();
        int reuslt = 0;
        if (contrastStatus != null && "2".equals(contrastStatus)) {
            reuslt = assuranceBusinessDataReportMapper.back(businessId, contrastStatus);
        } else {
            reuslt = assuranceBusinessDataReportMapper.back(businessId, "0");
        }
        iAntiCounterfeitingProcessRecord.add(NumberUtils.toLong(businessId + ""), "assurance_business_data_report", "申请财政退回", reason, String.valueOf(SecurityUtils.getLoginUser().getUser().getUserId()));
        dataExceptionNotify("业务数据申请财政退回", assuranceBusinessDataReport.getFirmName() + "业务数据申请财政退回!", businessId);
        return reuslt;
    }

    /**
     * 获取申请财政退回数据数量
     *
     * @return
     */
    @Override
    public List<AssuranceBusinessDataReport> selectApprovalReportCount(AssuranceBusinessDataReport report) {
        String idStr = report.getIds();
        if (idStr != null && idStr != "") {
            String[] ids = idStr.split(",");
            report.setIdList(ids);
        }
        if (report.getIdList().length > 0) {
            List<AssuranceBusinessDataReport> approvallist = assuranceBusinessDataReportMapper.selectApprovalReportCount(report);
            changeRegisterList(report, approvallist);
            return approvallist;
        }
        return null;
    }

    /**
     * 作废数据
     *
     * @param idstr
     * @param reason
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult voidBusinessData(String idstr, String reason) {
        int result = 0;
        if (idstr != null && idstr != "") {
            String[] ids = idstr.split(",");
            if (ids.length > 0) {
                for (int i = 0; i < ids.length; i++) {
                    Long businessId = Long.parseLong(ids[i]);
                    AssuranceBusinessDataReport report = selectReportByBusinessId(businessId);
                    if (report == null) {
                        return AjaxResult.error("鉴证业务报告错误!");
                    }
                    iAntiCounterfeitingProcessRecord.add(Long.parseLong(ids[i]), ProcessOptItemEnum.ASSURANCE_BUSINESS_DATA_REPORT.getItem(), ProcessOptResultsEnum.VOID.getName(), reason, SecurityUtils.getUsername());
                    result = assuranceBusinessDataReportMapper.voidBusinessData(Long.parseLong(ids[i]), reason);
                    //作废后申请财政退回
                    if (result == 1) {
                        String contrastStatus = report.getContrastStatus();
                        String dataStatus = report.getDataStatus();
                        if (contrastStatus != null) {
                            if (!("0".equals(contrastStatus)) && "0".equals(report.getApplyForFinancialRefund())) {
                                /*if ("3".equals(dataStatus) || "9".equals(dataStatus)) {
                                    back(Long.parseLong(ids[i]), "该数据作废，申请财政退回!");
                                }*/
                                back(Long.parseLong(ids[i]), "该数据作废，申请财政退回!");
                            }
                        }
                    }
                }
            }

        }
        return AjaxResult.success(result);
    }

    /**
     * 退回通过/不通过
     *
     * @param assuranceBusinessDataReport
     * @return
     */
    @Override
    public AjaxResult backPassOrNoPass(AssuranceBusinessDataReport assuranceBusinessDataReport) {
        int result = 0;
        String idstr = assuranceBusinessDataReport.getIds();
        String applyForFinancialRefund = assuranceBusinessDataReport.getApplyForFinancialRefund();
        String reason = assuranceBusinessDataReport.getReason();
        if (idstr != null && idstr != "") {
            String[] ids = idstr.split(",");
            if (ids.length > 0) {
                for (int i = 0; i < ids.length; i++) {
                    Long businessId = Long.parseLong(ids[i]);
                    AssuranceBusinessDataReport report = selectReportByBusinessId(businessId);
                    if (report == null) {
                        return AjaxResult.error("鉴证业务报告错误!");
                    }
                    result = assuranceBusinessDataReportMapper.backPassOrNoPass(businessId, applyForFinancialRefund);
                    long optItemId = businessId;
                    if (StringUtils.equals(applyForFinancialRefund, "2")) {
                        iAntiCounterfeitingProcessRecord.add(optItemId, "assurance_business_data_report", "财政退回通过", reason, String.valueOf(SecurityUtils.getLoginUser().getUser().getUserId()));
                    } else {
                        iAntiCounterfeitingProcessRecord.add(optItemId, "assurance_business_data_report", "财政退回不通过", reason, String.valueOf(SecurityUtils.getLoginUser().getUser().getUserId()));
                    }
                }
            }
        }

        return AjaxResult.success(result);
    }

    @Async
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void siaImportReport(List<AssuranceBusinessDataReport> assuranceBusinessDataReports, String taskNo, LoginUser loginUser) {
        log.info("========》》》》》》》》》》开始执行路径1导入");
        Map<String, Object> result = new HashMap<>();
        result.put("taskNo", taskNo);
        result.put("stageNum", 7);
        //"导入前准备" ,"数据必填字段校验" ,"类型及范围校验","事务所名称校验" ,"报备编码过滤","数据入库处理","导入完成"
        result.put("stageDetail", stageDetail);
        result.put("currentStage", 1);
        result.put("taskStatus", 0);
        result.put("finishMessage", "");
        result.put("failMessageList", "");
        String redisKey = "taskNo:" + taskNo;
        Long userId = loginUser.getUser().getUserId();
        try {
            redisCache.setCacheMap(redisKey, result);
            //设置10分钟后缓存失效
            redisCache.expire(redisKey, 60 * 10 * 60);
            Integer add = 0;//新增
            Integer ignore = 0;//忽略
            Integer reuse = 0;//重复
            Integer warn = 0;//异常
            if (assuranceBusinessDataReports != null && assuranceBusinessDataReports.size() > 0) {
                result.put("currentStage", 2);
                redisCache.setCacheMap(redisKey, result);
                //事务所名称集合
                Set<String> firmNameSet = new HashSet();
                //报备编号集合
                // List<String> reportCodeList = new ArrayList<>();
                //缺少必填字段的行记录
                List<Integer> nullLineList = new ArrayList<>();
                List<String> nullLineStrList = new ArrayList<>();
                log.info("========》》》》》》》》》》路径1，必填字段判断");
                for (int i = 0; i < assuranceBusinessDataReports.size(); i++) {
                    //必填字段判断
                    /*if (!BeanUtils.isRequiredParamNotNullString(assuranceBusinessDataReports.get(i))) {
                        nullLineList.add((i + 3));
                    }*/
                    List<String> nullParamList = BeanUtils.isRequiredParamNotNullStringReturn(assuranceBusinessDataReports.get(i), 1);

                    //20210513，用户反馈，扩展报备类型为”专项审计“和”其他“的，意见类型设为非必填
                    if (!StringUtils.equals(assuranceBusinessDataReports.get(i).getReportType(), ReportTypeEnum.CAPITAL_VERIFICATION.getValue())
                            && !StringUtils.equals(assuranceBusinessDataReports.get(i).getReportType(), ReportTypeEnum.SPECIAL_AUDIT_BUSINESS.getValue())
                            && !StringUtils.equals(assuranceBusinessDataReports.get(i).getReportType(), ReportTypeEnum.OTHER.getValue())
                            && StringUtils.isEmpty(assuranceBusinessDataReports.get(i).getOpinionType())) {
                        //20201109，用户反馈：事务所用户，录入业务数据，当选择报备类型为“验资业务”时，“意见类型”就应该为不必填
                        // 路径1应该也是同样的要求，所以额外做一下判断吧
                        nullLineList.add((i + 3));
                        nullParamList.add(BusinessFieldEnum.TYPE_OF_OPINION.getValue());
                    }

                    //20201127 报备类型为其他，cpa 不必填
                    if (!StringUtils.equals(assuranceBusinessDataReports.get(i).getReportType(), ReportTypeEnum.OTHER.getValue())) {

                        if (StringUtils.isEmpty(assuranceBusinessDataReports.get(i).getSignCertificateNo1())) {
                            nullLineList.add((i + 3));
                            nullParamList.add(BusinessFieldEnum.CERTIFICATE_NO_1_SIGNED.getValue());
                        }

                        if (StringUtils.isEmpty(assuranceBusinessDataReports.get(i).getSignerName1())) {
                            nullLineList.add((i + 3));
                            nullParamList.add(BusinessFieldEnum.SIGNED_CPA_1.getValue());
                        }

                        if (StringUtils.isEmpty(assuranceBusinessDataReports.get(i).getSignCertificateNo2())) {
                            nullLineList.add((i + 3));
                            nullParamList.add(BusinessFieldEnum.CERTIFICATE_NO_2_SIGNED.getValue());
                        }

                        if (StringUtils.isEmpty(assuranceBusinessDataReports.get(i).getSignCertificateNo2())) {
                            nullLineList.add((i + 3));
                            nullParamList.add(BusinessFieldEnum.SIGNED_CPA_2.getValue());

                        }
                    }

                   /* if (StringUtils.equals(assuranceBusinessDataReports.get(i).getReportType(), ReportTypeEnum.SPECIAL_AUDIT_BUSINESS.getValue())) {
                        //20201125，用户反馈：当选择报备类型为“专项审计业务”时，“备注”就应该为必填
                        if(StringUtils.isEmpty(assuranceBusinessDataReports.get(i).getOfficeRemarks())) {
                            nullLineList.add((i + 3));
                            nullParamList.add(BusinessFieldEnum.REMARK.getValue());
                        }*//*else if (assuranceBusinessDataReports.get(i).getOfficeRemarks().trim().length() > 10) {
                            nullLineList.add((i + 3));
                            // nullParamList.add(BusinessFieldEnum.REMARK.getValue());
                            String str = "excel第【" + (i + 3) + "】行备注长度超过10;" ;
                            nullLineStrList.add(str);
                        }*//*
                    }*/
                    String isSecuritiesBusiness = assuranceBusinessDataReports.get(i).getIsSecuritiesBusiness();
                    if (StringUtils.isNotEmpty(isSecuritiesBusiness)) {
                        //20200113 需求修改 为证券业务时 首次承接业务时间为必填
                        if (StringUtils.equals(isSecuritiesBusiness.trim(), "是")) {
                            String firstBusinessTime = assuranceBusinessDataReports.get(i).getFirstBusinessTime();
                            if (StringUtils.isEmpty(firstBusinessTime)) {
                                nullLineList.add((i + 3));
                                nullParamList.add(BusinessFieldEnum.TIME_OF_FIRST_UNDERTAKING_BUSINESS.getValue());
                            }
                        }
                    }

                    if (nullParamList != null && nullParamList.size() > 0) {
                        nullLineList.add((i + 3));
                        String str = "excel第【" + (i + 3) + "】行缺少必填字段：" + nullParamList.toString();
                        nullLineStrList.add(str);
                    }

                    if (assuranceBusinessDataReports.get(i) != null && org.apache.commons.lang3.StringUtils.isNotBlank(assuranceBusinessDataReports.get(i).getFirmName())) {
                        firmNameSet.add(assuranceBusinessDataReports.get(i).getFirmName());
                    }
                   /* if (assuranceBusinessDataReports.get(i) != null && org.apache.commons.lang3.StringUtils.isNotBlank(assuranceBusinessDataReports.get(i).getReportCode())) {
                        reportCodeList.add(assuranceBusinessDataReports.get(i).getReportCode());
                    }*/
                }
                if (nullLineList.size() > 0) {
                    result.put("taskStatus", 2);
                    result.put("finishMessage", "数据第：" + JSON.toJSONString(nullLineList) + " 行必填字段缺失，请检查模版中数据完整性");
                    result.put("failMessageList", nullLineStrList);
                    redisCache.setCacheMap(redisKey, result);
                    return;
                }
                //wmj 20201113 start 格式及范围校验
                List<String> failureItemList = new ArrayList<>();
                List<Integer> typeLineStrList = new ArrayList<>();
                for (int i = 0; i < assuranceBusinessDataReports.size(); i++) {
                    SimpleDateFormat yyyyMMddFormat = new SimpleDateFormat("yyyy-MM-dd");
                    StringBuilder sb = new StringBuilder();
                    //验资金额
                    AssuranceBusinessDataReport report = assuranceBusinessDataReports.get(i);
                    /*String capitalVerificationAmount = report.getCapitalVerificationAmount();
                    if(StringUtils.isNotEmpty(report.getCapitalVerificationAmount())){
                        Pattern pattern = Pattern.compile("^(([0-9][0-9]*)|(([0]\\.\\d{1,2}|[1-9][0-9]*\\.\\d{1,2})))$");
                        Matcher isNum = pattern.matcher(capitalVerificationAmount);
                        boolean matches = isNum.matches();
                        if (!matches) {
                            sb.append(BusinessFieldEnum.CAPITAL_VERIFICATION_AMOUNT.getValue());
                            sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                            sb.append(",");
                        }
                    }*/
                    //审计年度
                    /*String auditYear = report.getAuditYear();
                    if (StringUtils.isNotEmpty(auditYear)) {
                        Pattern pattern = Pattern.compile("[0-9]*");
                        Matcher isNum = pattern.matcher(auditYear);
                        boolean matches = isNum.matches();
                        if (!matches) {
                            //数字限制
                            sb.append(BusinessFieldEnum.AUDIT_YEAR.getValue());
                            sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                            sb.append(",");
                        } else {
                            //年度限制在1950-2050
                            Integer integer = Integer.valueOf(auditYear);
                            if (integer > 2050 || integer < 1950) {
                                sb.append(BusinessFieldEnum.AUDIT_YEAR.getValue());
                                sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                                sb.append(",");
                            }
                        }
                    }*/
                    //报告日期
                    String reportTime = report.getReportTime();
                    if (StringUtils.isNotEmpty(reportTime)) {
                        try {
                            if (reportTime.indexOf(".") > 1) {
                                reportTime = reportTime.trim().replace(".", "-");
                            }
                            if (reportTime.indexOf("/") > 1) {
                                reportTime = reportTime.trim().replace("/", "-");
                            }
                            Date date = yyyyMMddFormat.parse(reportTime);
                            reportTime = yyyyMMddFormat.format(date);
                            report.setReportTime(reportTime.trim());
                            String[] split = reportTime.split("-");
                            Integer year = Integer.valueOf(split[0]);
                            if (year < 1950 || year > 2200) {
                                sb.append(BusinessFieldEnum.DATE_OF_REPORT.getValue());
                                sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                                sb.append(",");
                            }
                        } catch (ParseException e) {
                            sb.append(BusinessFieldEnum.DATE_OF_REPORT.getValue());
                            sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                            sb.append(",");
                        }
                    }

                    //首次承接业务时间
                    String firstBusinessTime = report.getFirstBusinessTime();
                    if (StringUtils.isNotEmpty(firstBusinessTime)) {
                        try {
                            if (firstBusinessTime.indexOf(".") > 1) {
                                firstBusinessTime = firstBusinessTime.trim().replace(".", "-");
                            }
                            if (firstBusinessTime.indexOf("/") > 1) {
                                firstBusinessTime = firstBusinessTime.trim().replace("/", "-");
                            }
                            Date date = yyyyMMddFormat.parse(firstBusinessTime);
                            firstBusinessTime = yyyyMMddFormat.format(date);
                            report.setFirstBusinessTime(firstBusinessTime.trim());
                          /*  String[] split = firstBusinessTime.split("-");
                            Integer year = Integer.valueOf(split[0]);
                            if (year < 1950 || year > 2050) {
                                sb.append(BusinessFieldEnum.TIME_OF_FIRST_UNDERTAKING_BUSINESS.getValue());
                                sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                                sb.append(",");
                            }*/
                        } catch (ParseException e) {
                            sb.append(BusinessFieldEnum.TIME_OF_FIRST_UNDERTAKING_BUSINESS.getValue());
                            sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                            sb.append(",");
                        }
                    }

                    //收费金额
                    String chargeAmount = report.getChargeAmount();
                    if (StringUtils.isNotEmpty(chargeAmount)) {
                        //^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$
                        Pattern pattern = Pattern.compile("^((-?[0-9][0-9]*)|(([0]\\.\\d{1,2}|[1-9][0-9]*\\.\\d{1,2})))$");
                        Matcher isNum = pattern.matcher(chargeAmount);
                        boolean matches = isNum.matches();
                        if (!matches) {
                            sb.append(BusinessFieldEnum.CHARGE_AMOUNT.getValue());
                            sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                            sb.append(",");
                        }
                    }

                    //是否属于证券业务
                    String isSecuritiesBusiness = report.getIsSecuritiesBusiness();
                    if (StringUtils.isNotEmpty(isSecuritiesBusiness)) {
                        if (!("是".equals(isSecuritiesBusiness) || "否".equals(isSecuritiesBusiness) )) {
                            sb.append(BusinessFieldEnum.SECURITIES_BUSINESS.getValue());
                            sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                            sb.append(",");
                        }
                    }
                    if (sb.length() > 0) {
                        typeLineStrList.add(i + 3);
                        String officeImportControll = sb.substring(0, sb.length() - 1);
                        String str = "excel第【" + (i + 3) + "】行存在错误：" + officeImportControll;
                        failureItemList.add(str);
                    }
                }
                if (failureItemList.size() > 0) {
                    result.put("currentStage", 3);
                    result.put("taskStatus", 3);
                    result.put("finishMessage", "数据第：" + JSON.toJSONString(typeLineStrList) + " 行类型及范围填写错误，请检查模版中数据完整性");
                    result.put("failMessageList", failureItemList);
                    redisCache.setCacheMap(redisKey, result);
                    return;
                }
                //wmj 20201113 end
                result.put("currentStage", 4);
                redisCache.setCacheMap(redisKey, result);
                log.info("========》》》》》》》》》》路径1，事务所名称判断");
                //事务所名称判断
                List<HashMap<String, Object>> DBFirmNameIds = assuranceBusinessDataReportMapper.selectFirmNameIdsByNames(firmNameSet.toArray(new String[firmNameSet.size()]));
                //保存数据库中事务所名称集合
                List<String> DBFirmNames = new ArrayList<>();
                //保存事务所名称在数据库中的id对应关系
                Map<String, Long> firmNameIdMap = new HashMap<>();
                if (DBFirmNameIds != null) {
                    for (int i = 0; i < DBFirmNameIds.size(); i++) {
                        String firmName = DBFirmNameIds.get(i).get("firm_name").toString();
                        Long officeId = Long.parseLong(DBFirmNameIds.get(i).get("office_id").toString());
                        DBFirmNames.add(firmName);
                        firmNameIdMap.put(firmName, officeId);
                    }
                }
                if (DBFirmNames.size() != firmNameSet.size()) {
                    //size不一致，肯定是excel中的名称多于数据库中的名称，所以需要找出多出来的事务所名称进行提示
                    firmNameSet.removeAll(DBFirmNames);
                    result.put("taskStatus", 2);
                    result.put("finishMessage", "以下事务所不存在，请先将事务所信息录入系统：" + JSON.toJSONString(firmNameSet));
                    redisCache.setCacheMap(redisKey, result);
                    return;
                }
                result.put("currentStage", 5);
                redisCache.setCacheMap(redisKey, result);
                log.info("========》》》》》》》》》》路径1，重复报备编码查询");
                //重复报备编码查询,考虑到实际一天的数据量会超过千条，用in查询进行提前过滤，orcale最大支持1000个参数，mysql不限制个数，但对sql语句大小有要求，最大4M，所以搏一搏
               /* List<String> DBReportCodes = new ArrayList<>();
                if (reportCodeList != null && reportCodeList.size() > 0) {
                    DBReportCodes = assuranceBusinessDataReportMapper.selectReportCodesByCodes(reportCodeList.toArray(new String[reportCodeList.size()]));
                }*/
            /*    if (DBReportCodes != null && DBReportCodes.size() == reportCodeList.size()) {
                    //可以认定为同一个excel重复导入了，那就直接不处理，结束流程
                    //其实可以用文件的md5进行简单校验，过滤性能更好，但是说不准文件稍有改动，还是要进行数据库查询
                    result.put("taskStatus", 2);
                    result.put("finishMessage", "检测到导入的数据文件疑似已导入过的重复文件，请操作人员人工核实判断");
                    redisCache.setCacheMap(redisKey, result);
                    return;
                } else {

                }*/
                result.put("currentStage", 6);
                redisCache.setCacheMap(redisKey, result);
                //  reuse = DBReportCodes.size();
                log.info("========》》》》》》》》》》路径1，导入数据处理");
                //部分重复，则只处理不重复的数据
                for (int i = 0; i < assuranceBusinessDataReports.size(); i++) {
                    AssuranceBusinessDataReport firstData = assuranceBusinessDataReports.get(i);
                    firstData.setContrastStatus("2");
                    firstData.setDataStatus("3");
                    firstData.setImportTime(DateUtils.parseDateToStr(YYYY_MM_DD_HH_MM_SS, new Date()));
                    firstData.setDataUploadPath(DataInPathConstants.SIA_IMPORT);
                    String reportNoClean = "";
                    String reportNo = firstData.getReportNo();
                    if (StringUtils.isNotEmpty(reportNo)) {
                        firstData.setReportNoClean(StringUtils.removeSign(reportNo));
                        reportNoClean = StringUtils.removeSign(reportNo);
                    }else{
                        failureItemList.add("该报告报告文号错误!");
                        continue;
                    }

                    if (StringUtils.isNotEmpty(firstData.getOpinionType())) {
                        String opinionType = firstData.getOpinionType();
                        if (!BusinessOpinionItemEnum.checkAll(opinionType)) {
                            opinionType = opinionType + "(其他）";
                            firstData.setOpinionType(opinionType);
                        }
                    }
                    List<AssuranceBusinessDataRegisterSignature> assuranceBusinessDataRegisterSignatures = businessDataImportRegisterHandle(firstData);
                    if (assuranceBusinessDataRegisterSignatures != null && assuranceBusinessDataRegisterSignatures.size() > 0) {
                        firstData.setAssuranceBusinessDataRegisterSignatures(assuranceBusinessDataRegisterSignatures);
                    }
                    AntiCounterfeitingRegisteredOffice office = antiCounterfeitingRegisteredOfficeMapper.selectOfficeByFriName(firstData.getFirmName());
                    if (office != null) {
                        firstData.setOfficeId(office.getOfficeId());
                    }
              /*  if (DBReportCodes == null || !DBReportCodes.contains(firstData.getReportCode())) {

                }*/
                    //查询报告文号是否已经存在在数据库中，以此判断是否已经有了路径2的数据
                    //status：0草稿，1确认状态，2删除
                    //data_status：数据状态：0：不予报备，1：强审通过，2：数据异常，3：正常，4：作废，5：预上传，6：提交审核，7：审核通过，8：审核不通过,9：待确认
                   if(StringUtils.isNotEmpty(reportNoClean) ){
                       List<AssuranceBusinessDataReport> DBReports = assuranceBusinessDataReportMapper.selectImport2ReportList(reportNoClean);
                       if (DBReports != null && DBReports.size() > 0) {
                           //存入数据库，判断两份数据的主要字段是否一致，对主表数据进行匹配结果标记

                           AssuranceBusinessDataReport mainReport = DBReports.get(0);
                           //2020/11/16 新增改动 上柱协导入，录入的，对预上传数据不做任何改变，等预上传补充为正常后，在做比对判断
                           if ("5".equals(mainReport.getDataStatus()) || "6".equals(mainReport.getDataStatus())
                                   || "8".equals(mainReport.getDataStatus())) {
                               ignore++;
                               continue;
                           }

                                /*
                                    20201116，根据1114甲方提的要求：业务比对里，这两个文号是我故意把括号写成不一样的，既然系统已经默认这两个文号是一样的了，就不要再提示文号不一致需要修改，就默认替换成财政系统文号即可。
                                    所以将路径2的报告文号，直接更新成路径1的文号
                                 */
                           mainReport.setReportNo(firstData.getReportNo());

                               /* //为了导出报告修改历史时有注册师
                                changeAssuranceBusinessDataReportTemp(mainReport);*/

                           saveReportTempData(firstData, mainReport, 0, userId);

                           String contrastStatus = mainReport.getContrastStatus();
                           if (contrastStatus != null && "2".equals(contrastStatus)) {
                               firstData.setBusinessId(mainReport.getBusinessId());
                               firstData.setContrastStatus("2");
                               importSaveAssuranceBusinessDataReport(firstData, loginUser);
                           } else {
                               //对查询出的数据和导入的数据，进行必填字段的一致性匹配
                               String matchRes = reportDataTempMainMatch(firstData, mainReport);
                               /* if (StringUtils.equals(firstData.getReportType(), ReportTypeEnum.CAPITAL_VERIFICATION.getValue())) {
                                *//* if (!(StringUtils.equals(firstData.getCapitalVerificationAmount(), mainReport.getCapitalVerificationAmount()) &&
                                                StringUtils.equals(firstData.getCapitalVerificationCurrency(), mainReport.getCapitalVerificationCurrency()))) {
                                            matchRes = "不一致";
                                        }*//*
                        } else {
                            if (!StringUtils.equals(firstData.getOpinionType(), mainReport.getOpinionType())) {
                                matchRes = "不一致";
                            }
                        }*/
                      /*  if (!StringUtils.equals(firstData.getReportType(), ReportTypeEnum.CAPITAL_VERIFICATION.getValue()) && !StringUtils.equals(firstData.getOpinionType().trim(), mainReport.getOpinionType().trim())) {
                            matchRes = "不一致";
                        }*/
                               if (!StringUtils.equals(StringUtils.trim(firstData.getOpinionType()), StringUtils.trim(mainReport.getOpinionType()))) {
                                   matchRes = "不一致";
                               }
                               if (!StringUtils.equals(StringUtils.trim(firstData.getCustomerBusinessLicense()), StringUtils.trim(mainReport.getCustomerBusinessLicense()))) {
                                   matchRes = "不一致";
                               }
                               /*if (!StringUtils.equals(StringUtils.trim(firstData.getChargeAmount()), StringUtils.trim(mainReport.getChargeAmount()))) {
                                   matchRes = "不一致";
                               }*/

                               Double dou1 = null;
                               Double dou2 =null;
                               if(firstData.getChargeAmount() != null && StringUtils.trim(firstData.getChargeAmount()).length()>0){
                                   dou1 = Double.parseDouble(StringUtils.trim(firstData.getChargeAmount()));
                               }
                               if(mainReport.getChargeAmount() != null && StringUtils.trim(mainReport.getChargeAmount()).length()>0){
                                   dou2 = Double.parseDouble(StringUtils.trim(mainReport.getChargeAmount()));
                               }
                               if((dou1 == null && dou2 != null) || (dou1 != null && dou2 == null)){
                                   matchRes = "不一致";
                               }else if(dou1  != null && dou2 != null){
                                   if(dou1.doubleValue() != dou2.doubleValue()){
                                       matchRes = "不一致";
                                   }
                               }

                               if (!StringUtils.equals(StringUtils.trim(firstData.getFirstBusinessTime()), StringUtils.trim(mainReport.getFirstBusinessTime()))) {
                                   matchRes = "不一致";
                               }
                               if (mainReport.getAssuranceBusinessDataRegisterSignatures() != null) {
                                   if (mainReport.getAssuranceBusinessDataRegisterSignatures().size() > 0) {
                                       if (!StringUtils.equals(StringUtils.trim(firstData.getSignCertificateNo1()), StringUtils.trim(mainReport.getAssuranceBusinessDataRegisterSignatures().get(0).getRegistrationCertificateNo()))) {
                                           matchRes = "不一致";
                                       }
                                       if (!StringUtils.equals(StringUtils.trim(firstData.getSignerName1()), StringUtils.trim(mainReport.getAssuranceBusinessDataRegisterSignatures().get(0).getRegistrantName()))) {
                                           matchRes = "不一致";
                                       }
                                   }
                                   if (mainReport.getAssuranceBusinessDataRegisterSignatures().size() > 1) {
                                       if (!StringUtils.equals(StringUtils.trim(firstData.getSignCertificateNo2()), StringUtils.trim(mainReport.getAssuranceBusinessDataRegisterSignatures().get(1).getRegistrationCertificateNo()))) {
                                           matchRes = "不一致";
                                       }
                                       if (!StringUtils.equals(StringUtils.trim(firstData.getSignerName2()), StringUtils.trim(mainReport.getAssuranceBusinessDataRegisterSignatures().get(1).getRegistrantName()))) {
                                           matchRes = "不一致";
                                       }
                                   }

                               }
                               if (StringUtils.equals(matchRes, "不一致")) {
                                   mainReport.setDataStatus("9");
                                   dataExceptionNotify(mainReport.getCreateUser(), "数据匹配结果不一致", "编号:" + mainReport.getBusinessId() + "的业务数据数据与财政导入数据匹配结果不一致!", mainReport.getBusinessId());
                               } else {
                                   Integer matchCount = matchConditionalData(mainReport.getAuditYear(), mainReport.getReportType(), mainReport.getCustomerName(), mainReport.getCustomerBusinessLicense(), mainReport.getBusinessId());
                                   if (matchCount != null && matchCount > 0) {
                                       mainReport.setDataStatus("2");
                                   } else {
                                       mainReport.setDataStatus("3");
                                   }
                               }
                               //在更新主表数据之前，把主表数据备份到临时表去，类型是“更新”
                               // saveReportTempData(mainReport, mainReport, 1, userId);
                               mainReport.setDataMatchingResults(matchRes);
                               //如果已经存在了路径2的数据，现在导入路径1的数据，为了保证重复导入问题得到解决，需要直接更新主表中路径2的数据，将报备编码填上
                               mainReport.setReportCode(firstData.getReportCode());
                               mainReport.setFilingYear(firstData.getFilingYear());
                               mainReport.setFilingTime(firstData.getFilingTime());
                               mainReport.setReportStatus(firstData.getReportStatus());
                               mainReport.setUploadTime(firstData.getUploadTime());

                               mainReport.setContrastStatus("1");

                               mainReport.setScipaSaveReport(true);
                               mainReport.setImportTime(firstData.getImportTime());
                               importSaveAssuranceBusinessDataReport(mainReport, loginUser);
                           }

                       } else {
                           //查询“审计年度”+“报备类型”+“客户名称（被审验单位名称）/客户营业执照”是否有一致的其他数据
                           Integer matchRes = matchConditionalData(firstData.getAuditYear(), firstData.getReportType(), firstData.getCustomerName(), firstData.getCustomerBusinessLicense());
                           if (matchRes > 0) {
                               //有重复数据，将记录存入临时表和主表，并标记主表数据状态为异常
                               //数据状态：0：不予报备，1：强审通过，2：数据异常，3：正常，4：作废，5：预上传，6：提交审核，7：审核通过，8：审核不通过
                               firstData.setDataStatus("2");
                               warn += 1;
                           }
                           // 其实是先存入正式表，获取到id后再存储到临时表
                           generateAntiCode(firstData, loginUser);
                           saveReportTempData(firstData, firstData, 0, userId);
                       }
                       add += 1;
                   }
                }
            }
            log.info("========》》》》》》》》》》路径1，导入操作完成，导入成功");
            result.put("finishMessage", "导入操作完成，导入成功：" + add + "条，重复：" + reuse + "条，忽略：" + ignore + "条，" + "标记为异常状态：" + warn + "条");
            result.put("currentStage", 7);
            result.put("taskStatus", 1);
            redisCache.setCacheMap(redisKey, result);
        } catch (Exception e) {
            log.info("========》》》》》》》》》》路径1，导入操作发生异常");
            log.error(e.getMessage());
            e.printStackTrace();
            result.put("finishMessage", "应用系统发生异常，导入中止，请联系技术人员查看");
            result.put("taskStatus", 2);
            redisCache.setCacheMap(redisKey, result);
        }

    }

    @Override
    public Map<String, Object> getImportProgressByTaskNo(String taskNo) {
        return redisCache.getCacheMap("taskNo:" + taskNo);
    }

    /**
     * wym，抽取出来保存临时业务数据表记录的方法
     * status: 0 导入，1更新
     *
     * @param tempData
     * @param mainReport
     */
    private void saveReportTempData(AssuranceBusinessDataReport tempData, AssuranceBusinessDataReport mainReport, Integer status, Long userId) {
        AssuranceBusinessDataReportTemp dataReportTemp = new AssuranceBusinessDataReportTemp();
        dataReportTemp.setCreateTime(new Date());
        dataReportTemp.setCreateBy(userId);
        dataReportTemp.setStatus(status);
        dataReportTemp.setJson(JSON.toJSONString(tempData));
        dataReportTemp.setBussinessId(mainReport.getBusinessId());
        assuranceBusinessDataReportTempMapper.insertSelective(dataReportTemp);
    }

    /**
     * 路径1与路径2的数据匹配，判断的是业务数据的必填字段
     *
     * @param firstData  导入的路径1数据
     * @param secondData 数据库中已存在的路径2数据
     * @return
     */
    private String reportDataTempMainMatch(AssuranceBusinessDataReport firstData, AssuranceBusinessDataReport secondData) {
        String res = "一致";
        try {
            Class clazz = firstData.getClass();
            //获取object的所有属性
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                ParamNotNull paramNotNull = field.getAnnotation(ParamNotNull.class);
                if (paramNotNull != null) {
                    field.setAccessible(true);
                    Object firstValue = field.get(firstData);
                    Object secValue = field.get(secondData);
                    if ((firstValue == null && secValue != null && !"".equals(secValue.toString()))
                            || (secValue == null && firstValue != null && !"".equals(firstValue.toString()))) {
                        res = "不一致";
                        break;
                    }
                    if (firstValue != null && secValue != null && !firstValue.toString().trim().equals(secValue.toString().trim())) {
                        res = "不一致";
                        break;
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return res;
    }

    @Override
    public int noFilingOrCompulsoryApproval(Long businessId, int dataStatus, String strongReason) {
        return assuranceBusinessDataReportMapper.noFilingOrCompulsoryApproval(dataStatus, businessId, strongReason);
    }

    @Override
    public List<AssuranceBusinessDataReport> listApproval(AssuranceBusinessDataReport assuranceBusinessDataReport) {
        return assuranceBusinessDataReportMapper.listApproval(assuranceBusinessDataReport);
    }

    @Override
    public List<AssuranceBusinessDataReport> getAssuranceBusinessDataReport(String antiCounterfeitingCoding) throws Exception {
        List<AssuranceBusinessDataReport> list = assuranceBusinessDataReportMapper.getAssuranceBusinessDataReport(antiCounterfeitingCoding);
        return list;

    }

    /**
     * 获取审批不通过原因
     *
     * @param businessId
     * @return
     */
    @Override
    public String getFailedReason(Long businessId) {
        return antiCounterfeitingProcessRecordMapper.getReasonByItemIdAndItem(businessId, ProcessOptItemEnum.ASSURANCE_BUSINESS_DATA_REPORT.getItem(), ProcessOptResultsEnum.FAILED_TO_PASS_AUDIT.getName());
    }

    /**
     * 获取作废原因
     *
     * @param businessId
     * @return
     */
    @Override
    public String getVoidReason(Long businessId) {
        return antiCounterfeitingProcessRecordMapper.getReasonByItemIdAndItem(businessId, ProcessOptItemEnum.ASSURANCE_BUSINESS_DATA_REPORT.getItem(), ProcessOptResultsEnum.VOID.getName());
    }

    /**
     * 获取申请财政退回原因
     *
     * @param businessId
     * @return
     */
    @Override
    public String getApplyReturnReason(Long businessId) {
        return antiCounterfeitingProcessRecordMapper.getReasonByItemIdAndItem(businessId, ProcessOptItemEnum.ASSURANCE_BUSINESS_DATA_REPORT.getItem(), "申请财政退回");
    }

    /**
     * 获取申请财政退回不通过原因
     *
     * @param businessId
     * @return
     */
    @Override
    public String getApplyReturnNoReason(Long businessId) {
        return antiCounterfeitingProcessRecordMapper.getReasonByItemIdAndItem(businessId, ProcessOptItemEnum.ASSURANCE_BUSINESS_DATA_REPORT.getItem(), "财政退回不通过");
    }

    /**
     * 获取鉴证业务报告修改历史
     *
     * @param businessId
     * @return
     */
    @Override
    public List<AssuranceBusinessDataReportTemp> getEditHistoryByBusinessId(Long businessId) {
        return assuranceBusinessDataReportTempMapper.selectEditHistoryByBusinessId(businessId);
    }

    /**
     * 新增签字注册师
     *
     * @param assuranceBusinessDataReport
     */
    private void addSignatureRegistered(AssuranceBusinessDataReport assuranceBusinessDataReport) {
        List<AssuranceBusinessDataRegisterSignature> list = assuranceBusinessDataReport.getAssuranceBusinessDataRegisterSignatures();
        if (list != null && list.size() > 0) {
            for (AssuranceBusinessDataRegisterSignature assuranceBusinessDataRegisterSignature : list) {
                assuranceBusinessDataRegisterSignature.setBussinessId(assuranceBusinessDataReport.getBusinessId());
                String registrantName = assuranceBusinessDataRegisterSignature.getRegistrantName();
                if (StringUtils.isNotEmpty(registrantName)) {
                    assuranceBusinessDataRegisterSignatureMapper.insertSignatureRegistered(assuranceBusinessDataRegisterSignature);
                }
            }
        }
    }

   /* private void commonInputDataHandler(List<AssuranceBusinessDataReport> assuranceBusinessDataReports, DataPathEnum dataPathEnum) {
        if (assuranceBusinessDataReports != null && assuranceBusinessDataReports.size() > 0) {
            for (AssuranceBusinessDataReport dataReport : assuranceBusinessDataReports) {

            }
        }
    }*/

    /**
     * 事务所录入、导入业务报告数据统一校验
     *
     * @param assuranceBusinessDataReport
     * @return
     */
  /*  private AbnormalInfoEnum businessDataEntryVerify(AssuranceBusinessDataReport assuranceBusinessDataReport) {
        String reportNo = assuranceBusinessDataReport.getReportNo();
        if (StringUtils.isNotEmpty(reportNo)) {
            Integer reCount = reportNoRepeatCheck(reportNo);
            if (reCount != null && reCount > 0) {
                // 报告文号重复
                return AbnormalInfoEnum.REPORT_NO_REPEAT;
            } else {
                Integer matchFlag = matchConditionalData(assuranceBusinessDataReport.getFilingYear(), assuranceBusinessDataReport.getReportType(), assuranceBusinessDataReport.getCustomerName(), assuranceBusinessDataReport.getCustomerBusinessLicense());
                // 匹配对比失败
                if (matchFlag != null && matchFlag > 0) {
                    return AbnormalInfoEnum.ABNORMAL_IMPORTABLE;
                }
            }
        } else {
            return AbnormalInfoEnum.REPORT_NO_NON_EXISTENT;
        }
        return AbnormalInfoEnum.SUCCESS;
    }*/

    /**
     * 事务所预上传录入数据
     *
     * @param report
     * @return
     */
    @Override
    public AjaxResult preUploadSave(AssuranceBusinessDataReport report) {
        String reportNo = report.getReportNo();
        if (StringUtils.isEmpty(reportNo)) {
            return AjaxResult.error("缺少报告文号!");
        }else {
            String clearReportNo = StringUtils.removeSign(reportNo);
            if (StringUtils.isNotEmpty(clearReportNo)) {
                report.setReportNoClean(clearReportNo);
            } else {
                return AjaxResult.error("缺少报告文号!");
            }

            report.setDataStatus("5");
            report.setIsPreUpload(1);
            List<String> tarV = preUploadVerity(report);
            if (tarV != null && !tarV.isEmpty()) {
                return AjaxResult.error("预上传录入错误：" + String.join(",", tarV) + BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());

            }
            String columnStyleVerify = columnStyleVerify(report);
            if (report.getBusinessId() != null) {
                String preImportControll = preImportControll(report);
                if (StringUtils.isNotEmpty(preImportControll) || StringUtils.isNotEmpty(columnStyleVerify)) {
                    return AjaxResult.error("预上传补录错误：" + preImportControll + columnStyleVerify);
                }
            } else {
                if (StringUtils.isNotEmpty(columnStyleVerify)) {
                    return AjaxResult.error("预上传录入错误：" + columnStyleVerify);
                }
            }
            Integer checkCount = reportNoRepeatCheck(reportNo);
            if (checkCount != null && checkCount > 0) {
                if (report.getBusinessId() != null && report.getBusinessId() > 0L) {
                    LoginUser loginUser = SecurityUtils.getLoginUser();
                    Long officeId = loginUser.getUser().getOfficeId();
                    AssuranceBusinessDataReport assuranceBusinessDataReport = assuranceBusinessDataReportMapper.selectReportByReportNo(reportNo);
                    //
                    if ("5".equals(assuranceBusinessDataReport.getDataStatus()) && 1 == assuranceBusinessDataReport.getIsPreUpload() && officeId.equals(assuranceBusinessDataReport.getOfficeId())) {
                        report.setBusinessId(assuranceBusinessDataReport.getBusinessId());
                        report.setContrastStatus("0");
                        report.setDataStatus("3");
                        Integer matchCount = matchConditionalData(report.getAuditYear(), report.getReportType(), report.getCustomerName(), report.getCustomerBusinessLicense(), assuranceBusinessDataReport.getBusinessId());
                        if (matchCount != null && matchCount > 0) {
                            report.setDataStatus("2");
                            // generateAntiCode(report);
                   /*
                    AssuranceBusinessDataReport dataReport = importSaveAssuranceBusinessDataReport(report);
                    dataExceptionNotify("鉴证业务数据导入异常", "营业执照号：" + dataReport.getCustomerBusinessLicense() + "的客户导入数据异常!", dataReport.getBusinessId());
                    error++;*/
                        } else {
                            //generateAntiCode(report);
                        }
                        importSaveAssuranceBusinessDataReport(report, null);
                        AjaxResult.success(report.getBusinessId());
                    } else {
                        return AjaxResult.error("该报告文号重复");
                    }
                } else {
                    return AjaxResult.error("该报告文号重复");
                }
            } else {
                if (report.getBusinessId() != null && report.getBusinessId() > 0L) {
                    return AjaxResult.error("查无此报告文号");
                } else {
               /* Integer matchCount = matchConditionalData(report.getAuditYear(), report.getReportType(), report.getCustomerName(), report.getCustomerBusinessLicense());
                if (matchCount != null && matchCount > 0) {
                    report.setDataStatus("2");
                    // generateAntiCode(report);
                   *//* errorItem.append(errorLine);
                    errorItem.append(",");
                    AssuranceBusinessDataReport dataReport = importSaveAssuranceBusinessDataReport(report);
                    dataExceptionNotify("鉴证业务数据导入异常", "营业执照号：" + dataReport.getCustomerBusinessLicense() + "的客户导入数据异常!", dataReport.getBusinessId());
                    error++;*//*
                } else {
                    //generateAntiCode(report);
                }*/
                    generateAntiCode(report);
                }
            }
        }
        return AjaxResult.success(report.getBusinessId());
    }

    private List<String> preUploadVerity(AssuranceBusinessDataReport report) {
        List<String> checkList = checkPorpertiesHandler();
        List<String> tarV = new ArrayList<>();
        try {
            Class<? extends AssuranceBusinessDataReport> reportClass = report.getClass();
            tarV = checkList.stream().filter(s -> {
                try {
                    return StringUtils.isEmpty(reportClass.getDeclaredMethod("get" + StringUtils.capitalize(s)).invoke(report).toString());
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    return false;
                }
            }).map((s) -> {
                try {
                    Field filed = reportClass.getDeclaredField(s);
                    Excel excel = filed.getDeclaredAnnotation(Excel.class);
                    return excel.name()[0];
                } catch (NoSuchFieldException e) {
                    log.error(e.getMessage(), e);
                    return s;
                }
            }).collect(Collectors.toList());
        } catch (Exception e) {
            tarV.add("Excel模板数据异常，请确认好导入！");
        }
        return tarV;
    }

    /**
     * 预上传事务所业务数据导入
     *
     * @param list
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> preUploadImport(List<AssuranceBusinessDataReport> list) {
        Map<String, Object> result = new HashMap<>();
        Integer add = 0;
        Integer update = 0;
        Integer error = 0;
        Integer errorLine = 1;
        StringBuilder errorItem = new StringBuilder();
        List<String> failureItemList = new ArrayList<>();
        Integer fail = 0;

        if (list != null && list.size() > 0) {

            for (AssuranceBusinessDataReport report : list) {
                StringBuilder failureItem = new StringBuilder();
                errorLine++;
                report.setIsPreUpload(1);
                report.setDataStatus("5");
                report.setContrastStatus("0");
                report.setDataUploadPath(DataInPathConstants.OFFICE_INPUT);

                try {
                    //预上传必填校验
                    List<String> tarV = preUploadVerity(report);
                    if (tarV != null && !tarV.isEmpty()) {
                        failureItem.append("Excel第");
                        failureItem.append(errorLine);
                        failureItem.append("行错误：");
                        failureItem.append(String.join(",", tarV) + BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
                        failureItem.append(";");
                        fail++;
                        failureItemList.add(failureItem.toString());
                        continue;
                    }
                    //字段格式校验
                    String columnStyleVerify = columnStyleVerify(report);
                    if (StringUtils.isNotEmpty(columnStyleVerify)) {
                        failureItem.append("Excel第");
                        failureItem.append(errorLine);
                        failureItem.append("行错误：");
                        failureItem.append(columnStyleVerify);
                        failureItem.append(";");
                        fail++;
                        failureItemList.add(failureItem.toString());
                        continue;
                    }

                   /* String preImportControll = preImportControll(report);
                    if (preImportControll != null) {
                        failureItem.append("Excel第");
                        failureItem.append(errorLine);
                        failureItem.append("行错误：");
                        failureItem.append(preImportControll);
                        failureItem.append(";");
                        fail++;
                        failureItemList.add(failureItem.toString());
                        continue;
                    }*/
                    String reportNo = report.getReportNo();
                    if (StringUtils.isEmpty(reportNo)) {
                        failureItem.append("Excel第");
                        failureItem.append(errorLine);
                        failureItem.append("行错误：报告文号不存在;");
                        failureItemList.add(failureItem.toString());
                        fail++;
                        continue;
                    }

                    if (StringUtils.isNotEmpty(reportNo)) {
                        String clearReportNo = StringUtils.removeSign(reportNo);
                        if(StringUtils.isNotEmpty(clearReportNo)){
                            report.setReportNoClean(clearReportNo);
                        }else{
                            failureItem.append("Excel第");
                            failureItem.append(errorLine);
                            failureItem.append("行错误：报告文号不存在;");
                            failureItemList.add(failureItem.toString());
                            fail++;
                            continue;
                        }
                    }
                    Integer checkCount = reportNoRepeatCheck(reportNo);
                    if (checkCount != null && checkCount > 0) {
                       /* LoginUser loginUser = SecurityUtils.getLoginUser();
                        String username = loginUser.getUsername();
                        AntiCounterfeitingRegisteredOffice office = antiCounterfeitingRegisteredOfficeMapper.selectOfficeByPracticeCertificateNo(username);
                        AssuranceBusinessDataReport assuranceBusinessDataReport = assuranceBusinessDataReportMapper.selectReportByReportNo(reportNo);
                        //
                        if ("5".equals(assuranceBusinessDataReport.getDataStatus()) && 1 == assuranceBusinessDataReport.getIsPreUpload() && office.getOfficeId().equals(assuranceBusinessDataReport.getOfficeId())) {
                            report.setBusinessId(assuranceBusinessDataReport.getBusinessId());
                            report.setContrastStatus("0");
                            report.setDataStatus("3");
                            Integer matchCount = matchConditionalData(report.getAuditYear(), report.getReportType(), report.getCustomerName(), report.getCustomerBusinessLicense());
                            if (matchCount != null && matchCount > 0) {
                                report.setDataStatus("2");
                                // generateAntiCode(report);
                   *//* errorItem.append(errorLine);
                    errorItem.append(",");
                    AssuranceBusinessDataReport dataReport = importSaveAssuranceBusinessDataReport(report);
                    dataExceptionNotify("鉴证业务数据导入异常", "营业执照号：" + dataReport.getCustomerBusinessLicense() + "的客户导入数据异常!", dataReport.getBusinessId());
                    error++;*//*
                            } else {
                                //generateAntiCode(report);
                            }
                            importSaveAssuranceBusinessDataReport(report, null);
                            update++;
                        } else {
                            failureItem.append("Excel第");
                            failureItem.append(errorLine);
                            failureItem.append("行错误：报告文号重复;");
                            fail++;
                            failureItemList.add(failureItem.toString());
                            continue;
                        }*/
                        failureItem.append("Excel第");
                        failureItem.append(errorLine);
                        failureItem.append("行错误：报告文号重复;");
                        fail++;
                        failureItemList.add(failureItem.toString());
                        continue;
                    } else {
                        /*Integer matchCount = matchConditionalData(report.getAuditYear(), report.getReportType(), report.getCustomerName(), report.getCustomerBusinessLicense());
                        if (matchCount != null && matchCount > 0) {
                            report.setDataStatus("2");
                            error++;
                            errorItem.append(errorLine);
                            errorItem.append(",");
                      *//* AssuranceBusinessDataReport dataReport = importSaveAssuranceBusinessDataReport(report);
                    dataExceptionNotify("鉴证业务数据导入异常", "营业执照号：" + dataReport.getCustomerBusinessLicense() + "的客户导入数据异常!", dataReport.getBusinessId());
                    *//*
                        } else {
                            //generateAntiCode(report);
                        }*/
                        generateAntiCode(report);
                        add++;
                    }

                    /*AssuranceBusinessDataReport assuranceBusinessDataReport = assuranceBusinessDataReportMapper.selectReportByReportNo(reportNo);
                     *//*if (!Optional.ofNullable(assuranceBusinessDataReport).isPresent()) {
                    report.setContrastStatus("0");
                }*/
                } catch (Exception e) {
                    fail++;
                    failureItemList.add("Excel模板第" + errorLine + "行数据异常，请确认好导入！");
                }
            }

        }

        result.put("add", add);
        result.put("update", update);
        result.put("failureItemList", failureItemList);
        result.put("fail", fail);
        result.put("error", error);
        result.put("errorItem", errorItem.toString());
        return result;
    }

    /**
     * 事务所业务数据预上传补录
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> preUploadImportSupplement(List<AssuranceBusinessDataReport> list) {
        Map<String, Object> result = new HashMap<>();
        Integer add = 0;
        Integer update = 0;
        Integer error = 0;
        Integer errorLine = 1;
        StringBuilder errorItem = new StringBuilder();
        List<String> failureItemList = new ArrayList<>();
        Integer fail = 0;
        if (list != null && list.size() > 0) {
            for (AssuranceBusinessDataReport report : list) {
                errorLine++;
                StringBuilder failureItem = new StringBuilder();
                report.setIsPreUpload(1);
                report.setDataStatus("5");
                report.setContrastStatus("0");
                report.setDataUploadPath(DataInPathConstants.OFFICE_INPUT);
                //必填项控制
                try {
                    //预上传必填校验
                    List<String> tarV = preUploadVerity(report);
                    if (tarV != null && !tarV.isEmpty()) {
                        failureItem.append("Excel第");
                        failureItem.append(errorLine);
                        failureItem.append("行错误：");
                        failureItem.append(String.join(",", tarV) + BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
                        failureItem.append(";");
                        fail++;
                        failureItemList.add(failureItem.toString());
                        continue;
                    }
                    //字段格式校验
                    String columnStyleVerify = columnStyleVerify(report);
                    if (StringUtils.isNotEmpty(columnStyleVerify)) {
                        failureItem.append("Excel第");
                        failureItem.append(errorLine);
                        failureItem.append("行错误：");
                        failureItem.append(columnStyleVerify);
                        failureItem.append(";");
                        fail++;
                        failureItemList.add(failureItem.toString());
                        continue;
                    }

                    //报备类型判断必填
                    String preImportControll = preImportControll(report);
                    if (preImportControll != null) {
                        failureItem.append("Excel第");
                        failureItem.append(errorLine);
                        failureItem.append("行错误：");
                        failureItem.append(preImportControll);
                        failureItem.append(";");
                        fail++;
                        failureItemList.add(failureItem.toString());
                        continue;
                    }
                    String reportNo = report.getReportNo();
                    if (StringUtils.isEmpty(reportNo)) {
                        failureItem.append("Excel第");
                        failureItem.append(errorLine);
                        failureItem.append("行错误：");
                        failureItem.append("报告文号不存在;");
                        fail++;
                        failureItemList.add(failureItem.toString());
                        continue;
                    }

                    //根据报告文号查询数据
                    /*AssuranceBusinessDataReport assuranceBusinessDataReport = assuranceBusinessDataReportMapper.selectReportByReportNo(report.getReportNo());
                    List<AssuranceBusinessDataRegisterSignature> registerSignatures = assuranceBusinessDataRegisterSignatureMapper.selectAssuranceBusinessDataRegisterSignature(assuranceBusinessDataReport.getBusinessId());
                    if (assuranceBusinessDataReport != null) {
                        assuranceBusinessDataReport.setAssuranceBusinessDataRegisterSignatures(registerSignatures);
                        //不为空数据比较
                        String dataComparison = dataComparison(report, assuranceBusinessDataReport);
                        if (dataComparison != null) {
                            failureItem.append("Excel第");
                            failureItem.append(errorLine);
                            failureItem.append("行错误：");
                            failureItem.append(dataComparison);
                            failureItem.append(";");
                            fail++;
                            continue;
                        }
                    } else {
                        failureItem.append("Excel第");
                        failureItem.append(errorLine);
                        failureItem.append("行错误：");
                        failureItem.append("数据不存在");
                        failureItem.append(";");
                        fail++;
                        continue;
                    }
                    report.setStatus(1);
                    report.setBusinessId(assuranceBusinessDataReport.getBusinessId());
                    List<AssuranceBusinessDataRegisterSignature> assuranceBusinessDataRegisterSignatures = businessDataImportRegisterHandle(report);
                    report.setAssuranceBusinessDataRegisterSignatures(assuranceBusinessDataRegisterSignatures);
                    assuranceBusinessDataReportMapper.updateReport(report);
                    add++;*/

                    if (StringUtils.isNotEmpty(reportNo)) {
                        String clearReportNo = StringUtils.removeSign(reportNo);
                        if(StringUtils.isNotEmpty(clearReportNo)){
                            report.setReportNoClean(clearReportNo);
                        }else{
                            failureItem.append("Excel第");
                            failureItem.append(errorLine);
                            failureItem.append("行错误：");
                            failureItem.append("报告文号不存在;");
                            fail++;
                            failureItemList.add(failureItem.toString());
                            continue;
                        }
                    }
                    Integer checkCount = reportNoRepeatCheck(reportNo);
                    if (checkCount != null && checkCount > 0) {
                        LoginUser loginUser = SecurityUtils.getLoginUser();
                        Long officeId = loginUser.getUser().getOfficeId();

                        AssuranceBusinessDataReport assuranceBusinessDataReport = assuranceBusinessDataReportMapper.selectReportByReportNo(reportNo);
                        //
                        if ("5".equals(assuranceBusinessDataReport.getDataStatus()) && 1 == assuranceBusinessDataReport.getIsPreUpload() && officeId.equals(assuranceBusinessDataReport.getOfficeId())) {
                            report.setBusinessId(assuranceBusinessDataReport.getBusinessId());
                            report.setContrastStatus("0");
                            report.setDataStatus("3");
                            Integer matchCount = matchConditionalData(report.getAuditYear(), report.getReportType(), report.getCustomerName(), report.getCustomerBusinessLicense(), assuranceBusinessDataReport.getBusinessId());
                            if (matchCount != null && matchCount > 0) {
                                report.setDataStatus("2");
                      /*          errorItem.append(errorLine);
                                errorItem.append(",");
                                error++;*/
                                // generateAntiCode(report);
                   /*
                    AssuranceBusinessDataReport dataReport = importSaveAssuranceBusinessDataReport(report);
                    dataExceptionNotify("鉴证业务数据导入异常", "营业执照号：" + dataReport.getCustomerBusinessLicense() + "的客户导入数据异常!", dataReport.getBusinessId());
                    */
                            } else {
                                //generateAntiCode(report);
                            }
                            importSaveAssuranceBusinessDataReport(report, null);
                            update++;
                        } else {
                            failureItem.append("Excel第");
                            failureItem.append(errorLine);
                            failureItem.append("行错误：");
                            failureItem.append("该数据不是预上传状态");
                            failureItemList.add(failureItem.toString());
                            fail++;
                            continue;
                        }

                    } else {
                        /*Integer matchCount = matchConditionalData(report.getAuditYear(), report.getReportType(), report.getCustomerName(), report.getCustomerBusinessLicense());
                        if (matchCount != null && matchCount > 0) {
                            report.setDataStatus("2");
                            // generateAntiCode(report);
                   *//* errorItem.append(errorLine);
                    errorItem.append(",");
                    AssuranceBusinessDataReport dataReport = importSaveAssuranceBusinessDataReport(report);
                    dataExceptionNotify("鉴证业务数据导入异常", "营业执照号：" + dataReport.getCustomerBusinessLicense() + "的客户导入数据异常!", dataReport.getBusinessId());
                    error++;*//*
                        } else {
                            //generateAntiCode(report);
                        }
                        generateAntiCode(report);
                        add++;*/
                        failureItem.append("Excel第");
                        failureItem.append(errorLine);
                        failureItem.append("行错误：");
                        failureItem.append("没有录入，请先录入;");
                        failureItemList.add(failureItem.toString());
                        fail++;
                        continue;
                    }

                    /*AssuranceBusinessDataReport assuranceBusinessDataReport = assuranceBusinessDataReportMapper.selectReportByReportNo(reportNo);
                     *//*if (!Optional.ofNullable(assuranceBusinessDataReport).isPresent()) {
                    report.setContrastStatus("0");
                }*/

                } catch (Exception e) {
                    fail++;
                    failureItem.append(("Excel第" + errorLine + "行数据异常，请确认好导入！"));
                    failureItemList.add(failureItem.toString());
                }
            }
        }
        result.put("add", add);
        result.put("update", update);
        result.put("failureItemList", failureItemList);
        result.put("fail", fail);
        result.put("error", error);
        result.put("errorItem", errorItem.toString());
        return result;
    }

    /**
     * 校验属性处理
     *
     * @return
     */
    private List<String> checkPorpertiesHandler() {
        SysConfig sysConfig = iSysConfigService.selectConfigByConfigKey(ConfigKeyEnum.PRE_UPLOAD_KEY.getValue());
        String configValue = sysConfig.getConfigValue();
        List<String> checkList = new ArrayList<>();
        if (StringUtils.isNotEmpty(configValue)) {
            JSONObject configJson = JSON.parseObject(configValue);
            Set<String> keySet = configJson.keySet();
            checkList = keySet.stream().filter(s -> !StringUtils.equals(s, "assuranceBusinessDataRegisterSignatures") && configJson.getInteger(s) == 0).collect(Collectors.toList());
            JSONArray signatures = configJson.getJSONArray("assuranceBusinessDataRegisterSignatures");
            if (checkList == null) {
                checkList = new ArrayList<>();
            }
            if (signatures != null && signatures.size() > 0) {
                JSONObject indexS1 = signatures.getJSONObject(0);
                Integer registrantName1 = indexS1.getInteger("registrantName");
                if (registrantName1 == 0) {
                    checkList.add("signerName1");
                }
                Integer registrationCertificateNo1 = indexS1.getInteger("registrationCertificateNo");
                if (registrationCertificateNo1 == 0) {
                    checkList.add("signCertificateNo1");
                }
                if (signatures.size() > 1) {
                    JSONObject indexS2 = signatures.getJSONObject(1);
                    Integer registrantName2 = indexS2.getInteger("registrantName");
                    if (registrantName2 == 0) {
                        checkList.add("signerName2");
                    }
                    Integer registrationCertificateNo2 = indexS2.getInteger("registrationCertificateNo");
                    if (registrationCertificateNo2 == 0) {
                        checkList.add("signCertificateNo2");
                    }
                }
            }
        }
        return checkList;
    }

    /**
     * 上证所录入鉴证业务数据
     *
     * @param report
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult scipaSave(AssuranceBusinessDataReport report) {
        report.setContrastStatus("2");
        report.setDataStatus(report.getDataStatus() == null ? "3" : report.getDataStatus());
        String firmName = report.getFirmName();
        if (StringUtils.isNotEmpty(firmName)) {
            Long officeIdByFirmName = antiCounterfeitingRegisteredOfficeMapper.selectOfficeIdByFirmName(firmName);
            if (officeIdByFirmName != null && officeIdByFirmName > 0L) {
                report.setOfficeId(officeIdByFirmName);
            } else {
                return AjaxResult.error("事务所名称无法关联事务所!");
            }
        } else {
            return AjaxResult.error("未填写事务所名称!");
        }
       /* String reportCode = report.getReportCode();
        if (StringUtils.isNotEmpty(reportCode)) {
            Integer reportCodeCount = assuranceBusinessDataReportMapper.checkReportCode(reportCode);
            if (reportCodeCount != null && reportCodeCount > 0) {
                return AjaxResult.error("报备编码重复!");
            }
        }*/
        List<AssuranceBusinessDataRegisterSignature> assuranceBusinessDataRegisterSignatures = businessDataImportRegisterHandle(report);
        if (assuranceBusinessDataRegisterSignatures != null && assuranceBusinessDataRegisterSignatures.size() > 0) {
            report.setAssuranceBusinessDataRegisterSignatures(assuranceBusinessDataRegisterSignatures);
        }
        String reportNo = report.getReportNo();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUser().getUserId();
        if (StringUtils.isNotEmpty(reportNo)) {
            String reportNoClean = StringUtils.removeSign(reportNo);
            if(StringUtils.isNotEmpty(reportNoClean)){
                report.setReportNoClean(reportNoClean);
                List<AssuranceBusinessDataReport> DBReports = assuranceBusinessDataReportMapper.selectImport2ReportList(reportNoClean);
                if (DBReports != null && DBReports.size() > 0) {
                    //存入数据库，判断两份数据的主要字段是否一致，对主表数据进行匹配结果标记
                    AssuranceBusinessDataReport mainReport = DBReports.get(0);
                    //2020/11/16 新增改动 上柱协导入，录入的，对预上传数据不做任何改变，等预上传补充为正常后，在做比对判断
                    if ("5".equals(mainReport.getDataStatus()) || "6".equals(mainReport.getDataStatus())
                            || "8".equals(mainReport.getDataStatus())) {
                        return AjaxResult.error("该报告不是正常未比对状态!");
                    }
             /*   //为了导出报告修改历史时有注册师
               changeAssuranceBusinessDataReportTemp(mainReport);
*/
                    //保存上柱协录入的数据
                    saveReportTempData(report, mainReport, 0, userId);

                    String contrastStatus = mainReport.getContrastStatus();
                    if (contrastStatus != null && "2".equals(contrastStatus)) {
                        report.setBusinessId(mainReport.getBusinessId());
                        report.setContrastStatus("2");
                        //替换上柱协录入的数据，是路径1录入，这一次替换，增加修改次数
                        importSaveAssuranceBusinessDataReport(report, loginUser);
                    } else {

                        //上柱协录入路径2 ，事务所已录入，不修改事务所数据，不增加修改次数，修改一致性，比对，数据状态
                        //对查询出的数据和导入的数据，进行必填字段的一致性匹配
                        String matchRes = reportDataTempMainMatch(report, mainReport);
                    /*if (!StringUtils.equals(report.getCapitalVerificationAmount(), mainReport.getCapitalVerificationAmount()) ||
                            !StringUtils.equals(report.getCapitalVerificationCurrency(), mainReport.getCapitalVerificationCurrency())
                    ) {
                        matchRes = "不一致";
                    }*/

                        if (!StringUtils.equals(StringUtils.trim(report.getOpinionType()), StringUtils.trim(mainReport.getOpinionType()))) {
                            matchRes = "不一致";
                        }
                        if (!StringUtils.equals(StringUtils.trim(report.getCustomerBusinessLicense()), StringUtils.trim(mainReport.getCustomerBusinessLicense()))) {
                            matchRes = "不一致";
                        }

                       /* if (!StringUtils.equals(StringUtils.trim(report.getChargeAmount()), StringUtils.trim(mainReport.getChargeAmount()))) {
                            matchRes = "不一致";
                        }*/
                        Double dou1 = null;
                        Double dou2 =null;
                        if(report.getChargeAmount() != null && StringUtils.trim(report.getChargeAmount()).length()>0){
                            dou1 = Double.parseDouble(StringUtils.trim(report.getChargeAmount()));
                        }
                        if(mainReport.getChargeAmount() != null && StringUtils.trim(mainReport.getChargeAmount()).length()>0){
                            dou2 = Double.parseDouble(StringUtils.trim(mainReport.getChargeAmount()));
                        }
                        if((dou1 == null && dou2 != null) || (dou1 != null && dou2 == null)){
                            matchRes = "不一致";
                        }else if(dou1  != null && dou2 != null){
                            if(dou1.doubleValue() != dou2.doubleValue()){
                                matchRes = "不一致";
                            }
                        }

                        if (!StringUtils.equals(StringUtils.trim(report.getFirstBusinessTime()), StringUtils.trim(mainReport.getFirstBusinessTime()))) {
                            matchRes = "不一致";
                        }

                        if (mainReport.getAssuranceBusinessDataRegisterSignatures() != null) {
                            if (mainReport.getAssuranceBusinessDataRegisterSignatures().size() > 0) {
                                if (!StringUtils.equals(StringUtils.trim(report.getSignCertificateNo1()), StringUtils.trim(mainReport.getAssuranceBusinessDataRegisterSignatures().get(0).getRegistrationCertificateNo()))) {
                                    matchRes = "不一致";
                                }
                                if (!StringUtils.equals(StringUtils.trim(report.getSignerName1()), StringUtils.trim(mainReport.getAssuranceBusinessDataRegisterSignatures().get(0).getRegistrantName()))) {
                                    matchRes = "不一致";
                                }
                            }
                            if (mainReport.getAssuranceBusinessDataRegisterSignatures().size() > 1) {
                                if (!StringUtils.equals(StringUtils.trim(report.getSignCertificateNo2()), StringUtils.trim(mainReport.getAssuranceBusinessDataRegisterSignatures().get(1).getRegistrationCertificateNo()))) {
                                    matchRes = "不一致";
                                }
                                if (!StringUtils.equals(StringUtils.trim(report.getSignerName2()), StringUtils.trim(mainReport.getAssuranceBusinessDataRegisterSignatures().get(1).getRegistrantName()))) {
                                    matchRes = "不一致";
                                }
                            }

                        }

                        if (StringUtils.equals(matchRes, "不一致")) {
                            mainReport.setDataStatus("9");
                            dataExceptionNotify(mainReport.getCreateUser(), "数据匹配结果不一致", "编号:" + mainReport.getBusinessId() + "的业务数据数据与财政导入数据匹配结果不一致!", mainReport.getBusinessId());
                        } else {
                            Integer matchCount = matchConditionalData(mainReport.getAuditYear(), mainReport.getReportType(), mainReport.getCustomerName(), mainReport.getCustomerBusinessLicense(), mainReport.getBusinessId());
                            if (matchCount != null && matchCount > 0) {
                                mainReport.setDataStatus("2");
                            } else {
                                mainReport.setDataStatus("3");
                            }
                        }
                        //在更新主表数据之前，把主表数据备份到临时表去，类型是“更新”
                        //在  importSaveAssuranceBusinessDataReport(mainReport, loginUser); 中存过更新记录一次
                        // saveReportTempData(mainReport, mainReport, 1, userId);

                        // 修改上柱协第二次导入后没修改数据的问题（主要无需比对情况）
                        mainReport.setDataMatchingResults(matchRes);
                        //如果已经存在了路径2的数据，现在导入路径1的数据，为了保证重复导入问题得到解决，需要直接更新主表中路径2的数据，将报备编码填上
                        mainReport.setReportCode(report.getReportCode());
                        mainReport.setFilingYear(report.getFilingYear());
                        mainReport.setFilingTime(report.getFilingTime());
                        mainReport.setReportStatus(report.getReportStatus());
                        mainReport.setUploadTime(report.getUploadTime());
                        mainReport.setContrastStatus("1");
                        mainReport.setScipaSaveReport(true);
                        importSaveAssuranceBusinessDataReport(mainReport, loginUser);
                    }
                } else {
                    //查询“审计年度”+“报备类型”+“客户名称（被审验单位名称）/客户营业执照”是否有一致的其他数据
                    Integer matchRes = matchConditionalData(report.getAuditYear(), report.getReportType(), report.getCustomerName(), report.getCustomerBusinessLicense());
                    if (matchRes > 0) {
                        //有重复数据，将记录存入临时表和主表，并标记主表数据状态为异常
                        //数据状态：0：不予报备，1：强审通过，2：数据异常，3：正常，4：作废，5：预上传，6：提交审核，7：审核通过，8：审核不通过
                        report.setDataStatus("2");
                    }
                    // 其实是先存入正式表，获取到id后再存储到临时表
                    generateAntiCode(report, loginUser);
                    //再存储到临时表
                    saveReportTempData(report, report, 0, userId);
                }
            }
        } else {
            return AjaxResult.error("报告文号不存!");
        }
        return AjaxResult.success(report.getBusinessId());
    }

    /**
     * 检查事务所名称
     *
     * @param firmName
     * @return
     */
    @Override
    public Long checkFirmName(String firmName) {
        return antiCounterfeitingRegisteredOfficeMapper.selectOfficeIdByFirmName(firmName);
    }

    /**
     * 事务所数据批量导入修改
     *
     * @param list
     * @return
     */
    @Override
    public Map<String, Object> officeImportUpdate(List<AssuranceBusinessDataReport> list) {
        Map<String, Object> result = new HashMap<>();
        Integer update = 0;
        Integer error = 0;
        Integer errorLine = 1;
        StringBuilder failureItem = new StringBuilder();
        StringBuilder errorItem = new StringBuilder();
        Integer fail = 0;
        //20201104，wym，优化错误提示语展示
        List<String> failureItemList = new ArrayList<>();

        if (list != null && list.size() > 0) {
            for (AssuranceBusinessDataReport report : list) {
                errorLine++;
                report.setDataStatus("3");
                report.setDataUploadPath(DataInPathConstants.OFFICE_IMPORT);

                try {

                    //批量修改报告，不判断报告文号重复，进行必填、单元格格式校验，
                    String reportNo = report.getReportNo();
                    String s = "";
                    //导入必填判断
                    String controllStr = officeImportControll(report);
                    if (controllStr != null) {
                        s += controllStr;
                    }
                    //字段格式校验
                    String columnStyleVerifyStr = columnStyleVerify(report);
                    if (columnStyleVerifyStr != null) {
                        s += columnStyleVerifyStr;
                    }
                    if (s.length() > 0) {
                        s.substring(0, s.length() - 1);

                    }
                //    String officeImportControllWithReportNo = officeImportControllWithReportNo(report);

                    if (s != null && s.length()>0) {
                        fail++;
                        String str = "excel第" + errorLine + "行错误：" + s;
                        failureItemList.add(str);
                        continue;
                    }
                    AssuranceBusinessDataReport assuranceBusinessDataReport = assuranceBusinessDataReportMapper.selectReportByReportNo(reportNo);
                    if (!Optional.ofNullable(assuranceBusinessDataReport).isPresent()) {
                        fail++;
                        String str = "excel第" + errorLine + "行错误：没有找到对应报告" ;
                        failureItemList.add(str);
                        continue;
                    } else if(!("9".equals(assuranceBusinessDataReport.getDataStatus() )||( "0".equals(assuranceBusinessDataReport.getContrastStatus())
                            && ("2".equals(assuranceBusinessDataReport.getDataStatus()) || "3".equals(assuranceBusinessDataReport.getDataStatus() )) ))){

                        fail++;
                        String str = "excel第" + errorLine + "行错误：该数据不能批量修改" ;
                        failureItemList.add(str);
                        continue;
                    }
                    report.setBusinessId(assuranceBusinessDataReport.getBusinessId());
                    if (StringUtils.isNotEmpty(reportNo)) {
                        String clearReportNo = StringUtils.removeSign(reportNo);
                        report.setReportNoClean(clearReportNo);
                    }
                    if("9".equals(assuranceBusinessDataReport.getDataStatus() )){
                        report.setDataStatus("9");
                    }else {
                        //内容匹配
                        Integer matchCount = matchConditionalData(report.getAuditYear(), report.getReportType(), report.getCustomerName(), report.getCustomerBusinessLicense(), assuranceBusinessDataReport.getBusinessId());
                        if (matchCount != null && matchCount > 0) {
                            report.setDataStatus("2");
                            errorItem.append(errorLine);
                            errorItem.append(",");
                            error++;
                    /*;
                    AssuranceBusinessDataReport dataReport = importSaveAssuranceBusinessDataReport(report);
                    dataExceptionNotify("鉴证业务数据导入异常", "营业执照号：" + dataReport.getCustomerBusinessLicense() + "的客户导入数据异常!", dataReport.getBusinessId());
                    */
                        }
                    }
                    importSaveAssuranceBusinessDataReport(report);
                    update++;
                } catch (Exception e) {
                    fail++;
                    log.info(e.getMessage());
                    failureItemList.add("Excel第" + errorLine + "行数据异常，请确认好导入！");
                }

            }

        }

        result.put("update", update);
        result.put("failureItem", failureItem.toString());
        result.put("failureItemList", failureItemList);
        result.put("fail", fail);
        result.put("error", error);
        result.put("errorItem", errorItem.toString());
        return result;
    }

    /**
     * 事务所数据比对导入
     *
     * @param list
     * @return
     */
    @Override
    public Map<String, Object> officeImport(List<AssuranceBusinessDataReport> list) {
        Map<String, Object> result = new HashMap<>();
        Integer add = 0;
        Integer error = 0;
        Integer errorLine = 1;
        StringBuilder failureItem = new StringBuilder();
        StringBuilder errorItem = new StringBuilder();
        Integer fail = 0;
        //20201104，wym，优化错误提示语展示
        List<String> failureItemList = new ArrayList<>();

        if (list != null && list.size() > 0) {
            for (AssuranceBusinessDataReport report : list) {
                errorLine++;
                report.setDataStatus("3");
                report.setDataUploadPath(DataInPathConstants.OFFICE_IMPORT);

                try {

                    //20201116，根据用户反馈，将报告文号重复的提示，与上方必填、单元格格式校验，放到一起提示，类似：第5行报告文号重复、审计年度未填写、联系电话格式错误
                    String reportNo = report.getReportNo();
                    String officeImportControllWithReportNo = officeImportControllWithReportNo(report);

                    if (officeImportControllWithReportNo != null) {
                        fail++;
                        String str = "excel第" + errorLine + "行错误：" + officeImportControllWithReportNo;
                        failureItemList.add(str);
                        continue;
                    }
                    AssuranceBusinessDataReport assuranceBusinessDataReport = assuranceBusinessDataReportMapper.selectReportByReportNo(reportNo);
                    if (!Optional.ofNullable(assuranceBusinessDataReport).isPresent()) {
                        report.setContrastStatus("0");
                    } else {
                        report.setContrastStatus("1");
                    }
                    if (StringUtils.isNotEmpty(reportNo)) {
                        String clearReportNo = StringUtils.removeSign(reportNo);
                        report.setReportNoClean(clearReportNo);
                    }
                    //内容匹配
                    Integer matchCount = matchConditionalData(report.getAuditYear(), report.getReportType(), report.getCustomerName(), report.getCustomerBusinessLicense());
                    if (matchCount != null && matchCount > 0) {
                        report.setDataStatus("2");
                        generateAntiCode(report);
                        errorItem.append(errorLine);
                        errorItem.append(",");
                        error++;
                    /*;
                    AssuranceBusinessDataReport dataReport = importSaveAssuranceBusinessDataReport(report);
                    dataExceptionNotify("鉴证业务数据导入异常", "营业执照号：" + dataReport.getCustomerBusinessLicense() + "的客户导入数据异常!", dataReport.getBusinessId());
                    */
                    } else {
                        Set<String> permissionSet = SecurityUtils.getLoginUser().getPermissions();
                        report.setStatus(1);
                        if (permissionSet.contains(PerssionCheckEnum.ASSURANCE_NEED_REVIEW.getPerssionKey())) {
                            report.setDataStatus("6");
                            importSaveAssuranceBusinessDataReport(report);
                        } else {
                            generateAntiCode(report);
                        }
                    }
                    add++;
                } catch (Exception e) {
                    fail++;
                    log.info(e.getMessage());
                    failureItemList.add("Excel第" + errorLine + "行数据异常，请确认好导入！");
                }

            }

        }

        result.put("add", add);
        result.put("failureItem", failureItem.toString());
        result.put("failureItemList", failureItemList);
        result.put("fail", fail);
        result.put("error", error);
        result.put("errorItem", errorItem.toString());
        return result;
    }
    /**
     * 根据鉴证业务表id获取录入数据和导入数据
     *
     * @param businessId 鉴证业务表id
     * @return 鉴证业务表报告录入数据和导入数据
     * @author wph 20200917
     */
    @Override
    public AjaxResult getTempAndBusinessData(Long businessId) {
        //先去鉴证业务表获取录入数据
        AssuranceBusinessDataReport assuranceBusinessDataReport = assuranceBusinessDataReportMapper.selectReportByBusinessId(businessId);
        //再去中间表获取导入数据
        String json = assuranceBusinessDataReportTempMapper.selectByBusinessId(businessId);
        //调整格式
        HashMap<String, Object> tempMap = new HashMap<>();
        if (assuranceBusinessDataReport != null) {
            tempMap.put("officeInput", assuranceBusinessDataReport);
        }
        if (StringUtils.isNotEmpty(json)) {
            try {
                tempMap.put("financeImport", JSON.parse(json));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (isOfficeData(assuranceBusinessDataReport) < 1) {
            return AjaxResult.success("无权限");
        }

        return AjaxResult.success(tempMap);
    }

    /**
     * 判断在事务所登陆 下读取数据是否为本事务所数据
     *
     * @return
     * @pararm assuranceBusinessDataReport
     */
    @Override
    public int isOfficeData(AssuranceBusinessDataReport assuranceBusinessDataReport) {
        int flag = -1;
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Integer isOfficeAccount = user.getIsOfficeAccount();
        if (1 == isOfficeAccount) {
            Long officeId = user.getOfficeId();
            AntiCounterfeitingRegisteredOffice office = antiCounterfeitingRegisteredOfficeMapper.selectByOfficeId(officeId);
            if (office.getOfficeId().equals(assuranceBusinessDataReport.getOfficeId())) {
                flag = 1;
            }
        } else {
            flag = 1;
        }
        return flag;
    }

    /**
     * 审核鉴证业务数据
     *
     * @param report 鉴证业务数据报告
     * @author wph 20200921
     */
    @Override
    public AjaxResult auditImportReport(AssuranceBusinessDataReport report) {
        int result = 0;
        String idStr = report.getIds();
        if (StringUtils.isNotEmpty(idStr)) {
            String[] ids = idStr.split(",");
            if (ids.length > 0) {
                for (int i = 0; i < ids.length; i++) {
                    Long businessId = Long.parseLong(ids[i]);
                    AssuranceBusinessDataReport item = assuranceBusinessDataReportMapper.selectReportByBusinessId(businessId);
                    if (!"6".equals(item.getDataStatus())) {
                        return AjaxResult.error("选中中有非待审核数据");
                    }
                    item.setDataStatus(report.getDataStatus());
                    item.setOptReason(report.getOptReason());
                    result = auditOneImportReport(item);
                }
            }
        }
        return AjaxResult.success(result);
    }

    private int auditOneImportReport(AssuranceBusinessDataReport report) {
        int result = 0;
        report.setUpdateBy(SecurityUtils.getUsername());
        //审核未通过,调用方法在审核表添加相关数据
        if ("8".equals(report.getDataStatus())) {
            antiCounterfeitingProcessRecordImpl.add(report.getBusinessId(), "assurance_business_data_report", "审核不通过", report.getOptReason(), SecurityUtils.getUsername());
            //更新数据库审核状态
            result = assuranceBusinessDataReportMapper.auditImportReport(report);
        }
        //审核通过
        else if ("7".equals(report.getDataStatus())) {
            //判断操作项id和审核通过原因不为空
            if (report.getBusinessId() != null && report.getOptReason() != null && !"".equals(report.getOptReason())) {
                antiCounterfeitingProcessRecordImpl.add(report.getBusinessId(), "assurance_business_data_report", "审核通过", report.getOptReason(), SecurityUtils.getUsername());
            }
            //审核原因非必填,这里判断下,避免放进实体时报错
            else if (report.getOptReason() == null || "".equals(report.getOptReason())) {
                antiCounterfeitingProcessRecordImpl.add(report.getBusinessId(), "assurance_business_data_report", "审核通过", SecurityUtils.getUsername());
            }
            Long businessId = report.getBusinessId();
            AssuranceBusinessDataReport assuranceBusinessDataReport = assuranceBusinessDataReportMapper.selectReportByBusinessId(businessId);
            String antiCode = SecurityCodeGenerateUtils.generateSecurityCode(assuranceBusinessDataReport.getOfficeId(), assuranceBusinessDataReport.getBusinessId());
            report.setAntiCounterfeitingCoding(antiCode);
            //更新数据库审核状态
            result = assuranceBusinessDataReportMapper.auditImportReport(report);
        }
        return result;
    }

    /**
     * 获取待办事项  总数据（财政退回业务数据，需审核事务所业务数据，外省注册事务所审核数据，事务所联系人申请修改数据）
     */
    @Override
    public HashMap<String, Integer> getApproveCount() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Integer isOfficeAccount = user.getIsOfficeAccount();
        Long officeId = user.getOfficeId();
        HashMap<String, Integer> map = new HashMap<>();
        map.put("approvalCount", null);
        map.put("ApprovalOfficeCount", null);
        map.put("OfficeCount", null);
        map.put("officePhoneCount", null);
        map.put("approvalReportCount", null);
        map.put("applyContractCount", null);

        AssuranceBusinessDataReport report = new AssuranceBusinessDataReport();

        if (1 == isOfficeAccount) {

            //    AntiCounterfeitingRegisteredOffice office = antiCounterfeitingRegisteredOfficeMapper.selectByOfficeId(officeId);
            report.setDataStatus("9");
            report.setOfficeId(officeId);
            Integer approvalReportCount = assuranceBusinessDataReportMapper.selectApprovalOfficeReportCount(report, null);
            map.put("approvalReportCount", approvalReportCount);

            //申请修改联系人
            AntiCounterfeitingUpdateContract contract = new AntiCounterfeitingUpdateContract();
            contract.setOfficeId(officeId);
            List<LinkedHashMap<String, Object>> list = antiCounterfeitingUpdateContractMapper.exportList(contract);
            map.put("applyContractCount", list.size());
        } else {

            //获取需审核事务所待审核业务数据数量
            Integer approvalOfficeCount = 0;

            //获取待确认业务数据数量
            Integer approvalReportCount = 0;

            //获取需审核事务所待数量
            Integer OfficeCount = 0;

            //获取事务所申请修改联系人数量
            Integer officePhoneCount = 0;
            if (iCheckUserPowerService.noAdminHashRole(RoleEnum.OFFICE_GROUPING_ADMIN.getRoleKey())) {
                //事务所组长管理事务所id
                List<Long> longs = userService.selectUserOffice(user.getUserId());
                report.setOfficeId(null);

                report.setDataStatus("6");
                approvalOfficeCount = assuranceBusinessDataReportMapper.selectApprovalOfficeReportCount(report, longs);
                report.setDataStatus("9");
                approvalReportCount = assuranceBusinessDataReportMapper.selectApprovalOfficeReportCount(report, longs);
                officePhoneCount = assuranceBusinessDataReportMapper.selectApprovalOfficePhoneCount(longs);

                map.put("ApprovalOfficeCount", approvalOfficeCount);
                map.put("officePhoneCount", officePhoneCount);
                map.put("approvalReportCount", approvalReportCount);

            } else if (iCheckUserPowerService.noAdminHashRole(RoleEnum.CZYH.getRoleKey())) {
                //获取申请财政退回数据数量
                report.setApplyForFinancialRefund("1");
                List<AssuranceBusinessDataReport> approvallist = assuranceBusinessDataReportMapper.selectApprovalReportCount(report);
                int approvalCount = approvallist.size();
                map.put("approvalCount", approvalCount);
            } else {

                report.setOfficeId(null);
                report.setDataStatus("6");
                approvalOfficeCount = assuranceBusinessDataReportMapper.selectApprovalOfficeReportCount(report, null);
                report.setDataStatus("9");
                approvalReportCount = assuranceBusinessDataReportMapper.selectApprovalOfficeReportCount(report, null);
                OfficeCount = assuranceBusinessDataReportMapper.selectApprovalOfficeCount(null);
                officePhoneCount = assuranceBusinessDataReportMapper.selectApprovalOfficePhoneCount(null);

                map.put("ApprovalOfficeCount", approvalOfficeCount);
                map.put("OfficeCount", OfficeCount);
                map.put("officePhoneCount", officePhoneCount);
                map.put("approvalReportCount", approvalReportCount);
            }
        }
        return map;
    }

    @Override
    public Map<String, Object> getReportImgsByIds(String[] ids) {
        Map<String, Object> res = new HashMap<>();
        List<String> imgList = new ArrayList<>();
        boolean success = true;
        String message = "生成成功";
        try {
            //数组id去重
            ids = arryDuplication(ids);
            List<AssuranceBusinessDataReport> assuranceBusinessDataReports = assuranceBusinessDataReportMapper.selectReportListByBusinessIds(ids);
            for (int i = 0; i < assuranceBusinessDataReports.size(); i++) {
                AssuranceBusinessDataReport dataReport = assuranceBusinessDataReports.get(i);
                if (StringUtils.isNotEmpty(dataReport.getAntiCounterfeitingCoding())) {
                    byte[] pdfBytes = reportToPdfByte(dataReport);
                    if (pdfBytes != null) {
                        //转图片,PNG格式
                        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(pdfBytes);
                        ByteArrayOutputStream byteArrayOutputStream = PDFUtil.pdfStream2Image(byteArrayInputStream);
                        String imgBase64 = "data:image/png;base64," + Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
                        imgList.add(imgBase64);
                    }
                }
            }
            if (!(ids.length == imgList.size())) {
                message = "生成完毕，部分数据因不符合条件无法生成预览。";
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            success = false;
            message = "预览过程中发生异常，请联系技术人员查看！";
        }
        res.put("success", success);
        res.put("message", message);
        res.put("imgList", imgList);
        return res;

    }

    @Override
    public Map<String, byte[]> getReportZipByIds(String[] ids) {
        Map<String, byte[]> res = new HashMap<>();
        try {
            //数组id去重
            ids = arryDuplication(ids);
            List<AssuranceBusinessDataReport> assuranceBusinessDataReports = assuranceBusinessDataReportMapper.selectReportListByBusinessIds(ids);
            for (int i = 0; i < assuranceBusinessDataReports.size(); i++) {
                AssuranceBusinessDataReport dataReport = assuranceBusinessDataReports.get(i);
                if (StringUtils.isNotEmpty(dataReport.getAntiCounterfeitingCoding())) {
                    String fileName = dataReport.getReportNo() + ".pdf";
                    byte[] pdfBytes = reportToPdfByte(dataReport);
                    res.put(fileName, pdfBytes);
                }
            }
        } catch (Exception e) {
            log.error("getReportZipByIds===exception:" + e.getMessage());
            e.printStackTrace();
        }
        return res;

    }

    @Override
    public List<AssuranceBusinessDataReport> selectReportListByReportNo(String reportNo,String antiCounterfeitingCoding) {
        List<AssuranceBusinessDataReport> list = assuranceBusinessDataReportMapper.selectReportListByReportNo(reportNo,antiCounterfeitingCoding);
        return list;
    }

    //数组去重
    private String[] arryDuplication(String[] ids) {
        if (ids != null) {
            List<String> imei = Arrays.asList(ids);
            Set snSet = new HashSet(imei);
            ids = (String[]) snSet.toArray(new String[0]);
        }
        return ids;
    }

    //报告数据生成pdf字节数组
    private byte[] reportToPdfByte(AssuranceBusinessDataReport dataReport) throws Exception {
        byte[] pdfBytes = null;
        byte[] qrCode = generateQrCode(dataReport);
        if (qrCode != null) {
            String htmlContent = "";
            int lineHeight = 32;
            int count2line = 0;
            int countSinger = 0;
            boolean isShowSign1 = false;
            boolean isShowSign2 = false;
            boolean isShowSign3 = false;
            boolean isShowSign4 = false;
            //20201116，两个签字注师是在子实体里的，要拿出来重新赋值给主实体的字段才行
            List<AssuranceBusinessDataRegisterSignature> registerList = dataReport.getAssuranceBusinessDataRegisterSignatures();
            if (registerList.size() > 0) {
                dataReport.setSignCertificateNo1(registerList.get(0).getRegistrationCertificateNo());
                dataReport.setSignerName1(registerList.get(0).getRegistrantName());
                isShowSign1 = true;
                countSinger++;
            }
            if (registerList.size() > 1) {
                dataReport.setSignCertificateNo2(registerList.get(1).getRegistrationCertificateNo());
                dataReport.setSignerName2(registerList.get(1).getRegistrantName());
                isShowSign2 = true;
                countSinger++;
            }
            if (registerList.size() > 2) {
                dataReport.setSignCertificateNo3(registerList.get(2).getRegistrationCertificateNo());
                dataReport.setSignerName3(registerList.get(2).getRegistrantName());
                isShowSign3 = true;
                countSinger++;
            }
            if (registerList.size() > 3) {
                dataReport.setSignCertificateNo4(registerList.get(3).getRegistrationCertificateNo());
                dataReport.setSignerName4(registerList.get(3).getRegistrantName());
                isShowSign4 = true;
                countSinger++;
            }
            AntiCounterfeitingRegisteredOffice office = antiCounterfeitingRegisteredOfficeMapper.selectByPrimaryKey(dataReport.getOfficeId());
            String operatorNumber = "";
            SysUser sysUser = new SysUser();
            sysUser.setOfficeId(office.getOfficeId());
            sysUser.setIsOfficeAdmin(1);
            sysUser.setIsOfficeAccount(1);
            List<SysUser> list = userService.selectOfficeUserList(sysUser);
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    String tel = list.get(i).getTelephone();
                    if (tel != null) {
                        operatorNumber = tel;
                        break;
                    }
                }
            }

            String mailingAddress = office.getMailingAddress();
            String fireName = dataReport.getFirmName();
            String reportNo = dataReport.getReportNo();
            String customerName = dataReport.getCustomerName();
            String remark = dataReport.getOfficeRemarks();
            //判断是否会因为换行和注册师太多导致页面超出，动态调整高度
            //21个中文就会换行，字符长度限制也就是 21*2 = 42
            if (StringUtils.getStrByteLength(fireName) > 42) {
                count2line++;
            }
            if (StringUtils.getStrByteLength(customerName) > 42) {
                count2line++;
            }
            if (StringUtils.getStrByteLength(mailingAddress) > 42) {
                count2line++;
            }
            if (countSinger > 3 && count2line < 3) {
                lineHeight = 28;
            }
            if (countSinger > 3 && count2line > 2) {
                lineHeight = 26;
            }
            boolean isShowCW = false;
            boolean isShowQT = false;
            boolean isShowYZ = false;
            boolean isShowZX = false;
            boolean isShowNK = false;
            boolean isShowAuditYear = false;
            boolean isShowRemark = false;

            if (ReportTypeEnum.OTHER.getValue().equals(dataReport.getReportType())) {
                isShowQT = true;
            } else if (ReportTypeEnum.CAPITAL_VERIFICATION.getValue().equals(dataReport.getReportType())) {
                isShowYZ = true;
            } else if (ReportTypeEnum.SPECIAL_AUDIT_BUSINESS.getValue().equals(dataReport.getReportType())) {
                isShowZX = true;
                isShowRemark = true;
            } else if (ReportTypeEnum.INTERNAL_CONTROL_ASSURANCE_OF_LISTED_COMPANIES.getValue().equals(dataReport.getReportType())) {
                isShowNK = true;
            } else {
                isShowCW = true;
                isShowAuditYear = true;
            }
            String picture = "data:image/png;base64," + Base64.getEncoder().encodeToString(qrCode);

            Context ctx = new Context();
            ctx.setVariable("lineHeight", lineHeight);
            ctx.setVariable("isShowCW", isShowCW);
            ctx.setVariable("isShowQT", isShowQT);
            ctx.setVariable("isShowYZ", isShowYZ);
            ctx.setVariable("isShowZX", isShowZX);
            ctx.setVariable("isShowNK", isShowNK);
            ctx.setVariable("picture", picture);
            ctx.setVariable("antiCode", dataReport.getAntiCounterfeitingCoding());
            ctx.setVariable("customerName", customerName);
            ctx.setVariable("isShowAuditYear", isShowAuditYear);
            ctx.setVariable("auditYear", dataReport.getAuditYear());
            ctx.setVariable("isShowRemark", isShowRemark);
            ctx.setVariable("remark", remark);
            ctx.setVariable("reportNo", reportNo);
            ctx.setVariable("isShowSign1", isShowSign1);
            ctx.setVariable("signerName1", dataReport.getSignerName1());
            ctx.setVariable("signCertificateNo1", dataReport.getSignCertificateNo1());
            ctx.setVariable("isShowSign2", isShowSign2);
            ctx.setVariable("signerName2", dataReport.getSignerName2());
            ctx.setVariable("signCertificateNo2", dataReport.getSignCertificateNo2());
            ctx.setVariable("isShowSign3", isShowSign3);
            ctx.setVariable("signerName3", dataReport.getSignerName3());
            ctx.setVariable("signCertificateNo3", dataReport.getSignCertificateNo3());
            ctx.setVariable("isShowSign4", isShowSign4);
            ctx.setVariable("signerName4", dataReport.getSignerName4());
            ctx.setVariable("signCertificateNo4", dataReport.getSignCertificateNo4());
            ctx.setVariable("fireName", fireName);
            ctx.setVariable("contactNumber", operatorNumber);
            ctx.setVariable("mailingAddress", mailingAddress);

            htmlContent = templateEngine.process(reportTemplateName, ctx);
            //   System.out.println(htmlContent);
            //生成pdf字符数组
            pdfBytes = pdfDocumentGenerator.generate2byte(htmlContent);
        }
        return pdfBytes;
    }

    /**
     * 验证币种
     *
     * @param cur
     * @return
     */
    private boolean checkCurrency(String cur) {
        String currencys = sysDictDataMapper.selectGourpConctByType("currency");
        return currencys.contains("," + cur + ",");
    }

    /**
     * 预上传导入控制
     *
     * @param report
     * @return
     */
    private String preImportControll(AssuranceBusinessDataReport report) {
        StringBuilder sb = new StringBuilder();
        String reportType = report.getReportType();
        if (StringUtils.isNotEmpty(reportType)) {
            if (!ReportTypeEnum.checkAll(reportType.trim())) {
                sb.append(BusinessFieldEnum.REPORT_TYPE);
                sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                sb.append(",");
            }

            if (StringUtils.equals(reportType, ReportTypeEnum.CAPITAL_VERIFICATION.getValue())) {
                String capitalVerificationAmount = report.getCapitalVerificationAmount();
                if (StringUtils.isEmpty(capitalVerificationAmount)) {
                    sb.append(BusinessFieldEnum.CAPITAL_VERIFICATION_AMOUNT.getValue());
                    sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
                    sb.append(",");
                }
                String capitalVerificationCurrency = report.getCapitalVerificationCurrency();
                if (StringUtils.isEmpty(capitalVerificationCurrency)) {
                    sb.append(BusinessFieldEnum.CURRENCY_OF_CAPITAL_VERIFICATION.getValue());
                    sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
                    sb.append(",");
                }

            } else {
                if (StringUtils.isEmpty(report.getOpinionType())) {
                    sb.append(BusinessFieldEnum.TYPE_OF_OPINION.getValue());
                    sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
                    sb.append(",");
                }
            }
            if (!StringUtils.equals(reportType, ReportTypeEnum.CAPITAL_VERIFICATION.getValue()) && !StringUtils.equals(reportType, ReportTypeEnum.SPECIAL_AUDIT_BUSINESS.getValue()) && !StringUtils.equals(reportType, ReportTypeEnum.OTHER.getValue())) {
                String auditYear = report.getAuditYear();
                if (StringUtils.isEmpty(auditYear)) {
                    sb.append(BusinessFieldEnum.AUDIT_YEAR.getValue());
                    sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
                    sb.append(",");
                }
            }
            //20201125 需求修改 专项审计 备注必填
            if (StringUtils.equals(reportType, ReportTypeEnum.SPECIAL_AUDIT_BUSINESS.getValue())) {
                String remark = report.getOfficeRemarks();
                if (StringUtils.isEmpty(remark)) {
                    sb.append(BusinessFieldEnum.REMARK.getValue());
                    sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
                    sb.append(",");
                }/* else {
                    if (remark.trim().length() > 10) {
                        sb.append(BusinessFieldEnum.REMARK.getValue());
                        sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                        sb.append(",");
                    }
                }*/
            }
        }
      /*  String isSecuritiesBusiness = report.getIsSecuritiesBusiness();
        if (StringUtils.isNotEmpty(isSecuritiesBusiness)) {
            //20200113 需求修改 为证券业务时 首次承接业务时间为必填
            if (StringUtils.equals(isSecuritiesBusiness.trim(), "是")) {
                String firstBusinessTime = report.getFirstBusinessTime();
                if (StringUtils.isEmpty(firstBusinessTime)) {
                    sb.append(BusinessFieldEnum.TIME_OF_FIRST_UNDERTAKING_BUSINESS.getValue());
                    sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
                    sb.append(",");
                }
            }
        }*/
        if (sb.length() > 0) {
            return sb.substring(0, sb.length() - 1);
        }
        return null;
    }

    /**
     * 业务报告字段格式校验
     *
     * @param report
     * @return
     */
    private String columnStyleVerify(AssuranceBusinessDataReport report) {
        SimpleDateFormat yyyyMMddFormat = new SimpleDateFormat("yyyy-MM-dd");
        StringBuilder sb = new StringBuilder();
        String reportType = report.getReportType();
        String opinionType = report.getOpinionType();
        String capitalVerificationCurrency = report.getCapitalVerificationCurrency();

        if (StringUtils.isNotEmpty(reportType)) {
            if (!ReportTypeEnum.checkAll(reportType.trim())) {
                sb.append(BusinessFieldEnum.REPORT_TYPE);
                sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                sb.append(",");
            }
        }
        if (StringUtils.isNotEmpty(capitalVerificationCurrency)) {
            if (!checkCurrency(capitalVerificationCurrency.trim())) {
                sb.append(BusinessFieldEnum.CURRENCY_OF_CAPITAL_VERIFICATION.getValue());
                sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                sb.append(",");
            }
        }
        if (StringUtils.isNotEmpty(opinionType)) {
            if (!BusinessOpinionItemEnum.checkAll(opinionType.trim())) {
                opinionType = opinionType + "(其他）";
                report.setOpinionType(opinionType);
            }
        }

        //wmj 20201112 start
        String capitalVerificationAmount = report.getCapitalVerificationAmount();
        if (StringUtils.isNotEmpty(report.getCapitalVerificationAmount())) {
            Pattern pattern = Pattern.compile("^(([0-9][0-9]*)|(([0]\\.\\d{1,2}|[1-9][0-9]*\\.\\d{1,2})))$");
            Matcher isNum = pattern.matcher(capitalVerificationAmount.trim());
            boolean matches = isNum.matches();
            if (!matches) {
                sb.append(BusinessFieldEnum.CAPITAL_VERIFICATION_AMOUNT.getValue());
                sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                sb.append(",");
            }
        }

        //wmj 20201112 start
        // 202021127  审计年度 手动输入，不校验内容

       /* String auditYear = report.getAuditYear();
        if (StringUtils.isNotEmpty(auditYear)) {
            Pattern pattern = Pattern.compile("[0-9]*");
            Matcher isNum = pattern.matcher(auditYear.trim());
            boolean matches = isNum.matches();
            if (!matches) {
                //数字限制
                sb.append(BusinessFieldEnum.AUDIT_YEAR.getValue());
                sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
                sb.append(",");
            } else {
                //年度限制在1950-2050
                Integer integer = Integer.valueOf(auditYear.trim());
                if (integer > 2050 || integer < 1950) {
                    sb.append(BusinessFieldEnum.AUDIT_YEAR.getValue());
                    sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                    sb.append(",");
                }
            }
        }*/

        String reportTime = report.getReportTime();
        if (StringUtils.isNotEmpty(reportTime)) {
            try {
                if (reportTime.indexOf(".") > 1) {
                    reportTime = reportTime.trim().replace(".", "-");
                }
                if (reportTime.indexOf("/") > 1) {
                    reportTime = reportTime.trim().replace("/", "-");
                }
                Date date = yyyyMMddFormat.parse(reportTime.trim());
                reportTime = yyyyMMddFormat.format(date);
                report.setReportTime(reportTime.trim());
                String[] split = reportTime.trim().split("-");
                Integer year = Integer.valueOf(split[0]);
                if (year < 1950 || year > 2050) {
                    sb.append(BusinessFieldEnum.DATE_OF_REPORT.getValue());
                    sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                    sb.append(",");
                }
            } catch (ParseException e) {
                sb.append(BusinessFieldEnum.DATE_OF_REPORT.getValue());
                sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                sb.append(",");
            }
        }
        String firstBusinessTime = report.getFirstBusinessTime();
        if (StringUtils.isNotEmpty(firstBusinessTime)) {
            try {
                if (firstBusinessTime.indexOf(".") > 1) {
                    firstBusinessTime = firstBusinessTime.trim().replace(".", "-");
                }
                if (firstBusinessTime.indexOf("/") > 1) {
                    firstBusinessTime = firstBusinessTime.trim().replace("/", "-");
                }
                Date date = yyyyMMddFormat.parse(firstBusinessTime.trim());
                firstBusinessTime = yyyyMMddFormat.format(date);
                report.setFirstBusinessTime(firstBusinessTime.trim());

               /* String[] split = firstBusinessTime.trim().split("-");
                Integer year = Integer.valueOf(split[0]);
                if (year < 1950 || year > 2050) {
                    sb.append(BusinessFieldEnum.TIME_OF_FIRST_UNDERTAKING_BUSINESS.getValue());
                    sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                    sb.append(",");
                }*/
            } catch (ParseException e) {
                sb.append(BusinessFieldEnum.TIME_OF_FIRST_UNDERTAKING_BUSINESS.getValue());
                sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                sb.append(",");
            }
        }

        String chargeAmount = report.getChargeAmount();
        if (StringUtils.isNotEmpty(chargeAmount)) {
            Pattern pattern = Pattern.compile("^(([0-9][0-9]*)|(([0]\\.\\d{1,2}|[1-9][0-9]*\\.\\d{1,2})))$");
            Matcher isNum = pattern.matcher(chargeAmount.trim());
            boolean matches = isNum.matches();
            if (!matches) {
                sb.append(BusinessFieldEnum.CHARGE_AMOUNT.getValue());
                sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                sb.append(",");
            }
        }
        //wmj 20201112 end
        String isSecuritiesBusiness = report.getIsSecuritiesBusiness();
        if (StringUtils.isNotEmpty(isSecuritiesBusiness)) {
            if (!BusinessCommonYesNoEnum.checkAll(isSecuritiesBusiness.trim())) {
                sb.append(BusinessFieldEnum.SECURITIES_BUSINESS.getValue());
                sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                sb.append(",");
            }
        }
        if (sb.length() > 0) {
            return sb.substring(0, sb.length() - 1);
        }
        return null;
    }

    /**
     * 2020116，避免officeImportControll（）方法的控制被其他方法调用，在这里包装一层新方法，除了检测字段必填与格式是否正确外
     * 还要校验报告文号重复的问题
     */
    private String officeImportControllWithReportNo(AssuranceBusinessDataReport report) {
        String s = "";
        String reportNo = report.getReportNo();
        if (StringUtils.isEmpty(reportNo)){
            s += "报告文号为空,";
        }else{
            String reportNoClean = StringUtils.removeSign(reportNo);
            if(StringUtils.isEmpty(reportNoClean)){
                s += "报告文号为空,";
            }else{
                Integer checkCount = reportNoRepeatCheck(reportNo);
                if (checkCount != null && checkCount > 0) {
                    s += "报告文号重复,";
                }
            }
        }

        //导入必填判断
        String controllStr = officeImportControll(report);
        if (controllStr != null) {
            s += controllStr;
        }
        //字段格式校验
        String columnStyleVerifyStr = columnStyleVerify(report);
        if (columnStyleVerifyStr != null) {
            s += columnStyleVerifyStr;
        }
        if (s.length() > 0) {
            s.substring(0, s.length() - 1);
            return s;
        } else {
            return null;
        }
    }

    /**
     * 事务所导入必填控制
     *
     * @param report
     * @return
     */
    private String officeImportControll(AssuranceBusinessDataReport report) {
        StringBuilder sb = new StringBuilder();
        String reportType = report.getReportType();
        if (StringUtils.isEmpty(reportType)) {
            sb.append(BusinessFieldEnum.REPORT_TYPE);
            sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
            sb.append(",");
        } else {

            //wym，增加注释，如果报备类型是“验资业务”，则验资金额、验资币种字段需要必填
            if (StringUtils.equals(reportType, ReportTypeEnum.CAPITAL_VERIFICATION.getValue())) {
                String capitalVerificationAmount = report.getCapitalVerificationAmount();
                if (StringUtils.isEmpty(capitalVerificationAmount)) {
                    sb.append(BusinessFieldEnum.CAPITAL_VERIFICATION_AMOUNT.getValue());
                    sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
                    sb.append(",");
                }
                String capitalVerificationCurrency = report.getCapitalVerificationCurrency();
                if (StringUtils.isEmpty(capitalVerificationCurrency)) {
                    sb.append(BusinessFieldEnum.CURRENCY_OF_CAPITAL_VERIFICATION.getValue());
                    sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
                    sb.append(",");
                }
            } else {
                //20210513，用户反馈，扩展报备类型为”专项审计“和”其他“的，意见类型设为非必填
                if (!StringUtils.equals(reportType, ReportTypeEnum.OTHER.getValue())) {
                    //20201109，用户反馈：事务所用户，录入业务数据，当选择报备类型为“验资业务”时，“意见类型”就应该为不必填
                    if (StringUtils.isEmpty(report.getOpinionType())) {
                        sb.append(BusinessFieldEnum.TYPE_OF_OPINION.getValue());
                        sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
                        sb.append(",");
                    }
                }
            }

            //20201125 需求修改 专项审计 备注必填
            if (StringUtils.equals(reportType, ReportTypeEnum.SPECIAL_AUDIT_BUSINESS.getValue())) {
                String remark = report.getOfficeRemarks();
                if (StringUtils.isEmpty(remark)) {
                    sb.append(BusinessFieldEnum.REMARK.getValue());
                    sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
                    sb.append(",");
                } /*else {
                    if (remark.trim().length() > 10) {
                        sb.append(BusinessFieldEnum.REMARK.getValue());
                        sb.append(BusinessAbnormalInfoPromptEnum.WRONG_FILLING.getInfo());
                        sb.append(",");
                    }
                }*/
            }
        }

        //wmj 20201112 end
        String customerBusinessLicense = report.getCustomerBusinessLicense();
        if (StringUtils.isEmpty(customerBusinessLicense)) {
            sb.append(BusinessFieldEnum.BUSINESS_LICENSE_NO.getValue());
            sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
            sb.append(",");
        }
        String customerName = report.getCustomerName();
        if (StringUtils.isEmpty(customerName)) {
            sb.append(BusinessFieldEnum.CUSTOMER_NAME.getValue());
            sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
            sb.append(",");
        }
        String reportTime = report.getReportTime();
        if (StringUtils.isEmpty(reportTime)) {
            sb.append(BusinessFieldEnum.DATE_OF_REPORT.getValue());
            sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
            sb.append(",");
        }

        String placeOfIncorporation = report.getPlaceOfIncorporation();
        if (StringUtils.isEmpty(placeOfIncorporation)) {
            sb.append(BusinessFieldEnum.PLACEOFINCORPORATION.getValue());
            sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
            sb.append(",");
        }

        String businessAddress = report.getBusinessAddress();
        if (StringUtils.isEmpty(businessAddress)) {
            sb.append(BusinessFieldEnum.BUSINESSADDRESS.getValue());
            sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
            sb.append(",");
        }

        //20201127 当报备类型为其他时，cpa 为不必填
        if (StringUtils.isEmpty(reportType) || (StringUtils.isNotEmpty(reportType) && !StringUtils.equals(reportType, ReportTypeEnum.OTHER.getValue()))) {

            String signCertificateNo1 = report.getSignCertificateNo1();
            if (StringUtils.isEmpty(signCertificateNo1)) {
                sb.append(BusinessFieldEnum.CERTIFICATE_NO_1_SIGNED.getValue());
                sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
                sb.append(",");
            }
            String signerName1 = report.getSignerName1();
            if (StringUtils.isEmpty(signerName1)) {
                sb.append(BusinessFieldEnum.SIGNED_CPA_1.getValue());
                sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
                sb.append(",");
            }
            String signCertificateNo2 = report.getSignCertificateNo2();
            if (StringUtils.isEmpty(signCertificateNo2)) {
                sb.append(BusinessFieldEnum.CERTIFICATE_NO_2_SIGNED.getValue());
                sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
                sb.append(",");
            }
            String signerName2 = report.getSignerName2();
            if (StringUtils.isEmpty(signerName2)) {
                sb.append(BusinessFieldEnum.SIGNED_CPA_2.getValue());
                sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
                sb.append(",");
            }
        }

      /*  String chargeAmount = report.getChargeAmount();
        if (StringUtils.isEmpty(chargeAmount)) {
            sb.append(BusinessFieldEnum.CHARGE_AMOUNT.getValue());
            sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
            sb.append(",");
        }*/
        String isSecuritiesBusiness = report.getIsSecuritiesBusiness();
        if (StringUtils.isEmpty(isSecuritiesBusiness)) {
            sb.append(BusinessFieldEnum.SECURITIES_BUSINESS.getValue());
            sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
            sb.append(",");
        } else {
            //20200113 需求修改 为证券业务时 首次承接业务时间为必填
            if (StringUtils.equals(isSecuritiesBusiness.trim(), "是")) {
                String firstBusinessTime = report.getFirstBusinessTime();
                if (StringUtils.isEmpty(firstBusinessTime)) {
                    sb.append(BusinessFieldEnum.TIME_OF_FIRST_UNDERTAKING_BUSINESS.getValue());
                    sb.append(BusinessAbnormalInfoPromptEnum.NOT_FILLED_IN.getInfo());
                    sb.append(",");
                }
            }
        }
        if (sb.length() > 0) {
            return sb.substring(0, sb.length() - 1);
        }
        return null;
    }

    /**
     * 重载方法
     *
     * @param report
     */
    private void generateAntiCode(AssuranceBusinessDataReport report) {
        generateAntiCode(report, null);
    }

    /**
     * 生成防伪编码并保存
     *
     * @param report
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    protected synchronized void generateAntiCode(AssuranceBusinessDataReport report, LoginUser loginUser) {
        try {
            AssuranceBusinessDataReport dataReport = importSaveAssuranceBusinessDataReport(report, loginUser);
            //20201110,wym，修改编码生成规则
            String practiceCertificateNo = antiCounterfeitingRegisteredOfficeMapper.selectOfficePracticeCertificateNoByOfficeId(dataReport.getOfficeId());
            String antiCode = "";
            boolean isRepate = true;
            while (isRepate) {
                antiCode = SecurityCodeGenerateUtils.generateSecurityCodeNew(practiceCertificateNo);
                //生成之后比对一下数据库，如果重复了就再生成一个，直到不重复为止
                List<AssuranceBusinessDataReport> list = assuranceBusinessDataReportMapper.getAssuranceBusinessDataReport(antiCode);
                if (list.size() == 0) {
                    isRepate = false;
                }
            }

            assuranceBusinessDataReportMapper.updateAntiCodeByBusinessId(dataReport.getBusinessId(), antiCode);
        } catch (Exception e) {

        }
    }


    @Override
    public void makeAntiCode() {
        List<HashMap<String, Object>> list = assuranceBusinessDataReportMapper.selectAntiCodePlural();
        for (int i = 0; i < list.size(); i++) {
            HashMap<String, Object> map = list.get(i);
            String antiCode = map.get("anti_counterfeiting_coding").toString();
            List<AssuranceBusinessDataReport> reportlist = assuranceBusinessDataReportMapper.getAssuranceBusinessDataReport(antiCode);
            for (int y = 0; y < reportlist.size(); y++) {
                AssuranceBusinessDataReport report = reportlist.get(y);
                try {
                    //20201110,wym，修改编码生成规则
                    String practiceCertificateNo = antiCounterfeitingRegisteredOfficeMapper.selectOfficePracticeCertificateNoByOfficeId(report.getOfficeId());
                    String antiCodeItem = "";
                    boolean isRepate = true;
                    while (isRepate) {
                        antiCodeItem = SecurityCodeGenerateUtils.generateSecurityCodeNew(practiceCertificateNo);
                        //生成之后比对一下数据库，如果重复了就再生成一个，直到不重复为止
                        List<AssuranceBusinessDataReport> plurallist = assuranceBusinessDataReportMapper.getAssuranceBusinessDataReport(antiCodeItem);
                        if (plurallist.size() == 0) {
                            isRepate = false;
                        }
                    }
                    log.info("修改防伪编码： " + report.getBusinessId() + "旧：" + report.getAntiCounterfeitingCoding() + "新：" + antiCodeItem);
                    assuranceBusinessDataReportMapper.updateAntiCodeByBusinessId(report.getBusinessId(), antiCodeItem);
                } catch (Exception e) {

                }
            }
        }

    }

    /**
     * 上注协生成防伪码并保存
     *
     * @param report
     * @param scipa
     */
    @Transactional(rollbackFor = Exception.class)
    protected void generateAntiCode(AssuranceBusinessDataReport report, boolean scipa) {
        if (scipa) {
            AssuranceBusinessDataReport dataReport = importSaveAssuranceBusinessDataReport(report, true);
            //20201110,wym，修改编码生成规则
            String practiceCertificateNo = antiCounterfeitingRegisteredOfficeMapper.selectOfficePracticeCertificateNoByOfficeId(dataReport.getOfficeId());
            String antiCode = SecurityCodeGenerateUtils.generateSecurityCodeNew(practiceCertificateNo);
            //String antiCode = SecurityCodeGenerateUtils.generateSecurityCode(dataReport.getOfficeId(), dataReport.getBusinessId());
            assuranceBusinessDataReportMapper.updateAntiCodeByBusinessId(dataReport.getBusinessId(), antiCode);
        }
    }


    /**
     * 上注协保存或修改业务数据
     *
     * @param report
     * @param scipa
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    protected AssuranceBusinessDataReport importSaveAssuranceBusinessDataReport(AssuranceBusinessDataReport report,
                                                                                boolean scipa) {
        if (scipa) {
            Long businessId = report.getBusinessId();
            if (businessId != null && businessId > 0) {
                AssuranceBusinessDataReportTemp temp = new AssuranceBusinessDataReportTemp();
                temp.setBussinessId(report.getBusinessId());
                temp.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId());
                temp.setStatus(1);
                temp.setJson(JSON.toJSONString(report));
                assuranceBusinessDataReportTempMapper.insertSelective(temp);
                assuranceBusinessDataReportMapper.updateReport(report);
            } else {
                assuranceBusinessDataReportMapper.insertReport(report);
            }
            List<AssuranceBusinessDataRegisterSignature> assuranceBusinessDataRegisterSignatures = businessDataImportRegisterHandle(report);
            assuranceBusinessDataRegisterSignatureMapper.deleteByBusinessId(report.getBusinessId());
            assuranceBusinessDataRegisterSignatureMapper.batchInsertRegister(assuranceBusinessDataRegisterSignatures, report.getBusinessId());
        }
        return report;
    }

    /**
     * 重载方法
     *
     * @param report
     * @return
     */
    private AssuranceBusinessDataReport importSaveAssuranceBusinessDataReport(AssuranceBusinessDataReport report) {
        return importSaveAssuranceBusinessDataReport(report, null);
    }

    /**
     * 保存事务所业务数据
     *
     * @param report
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    protected AssuranceBusinessDataReport importSaveAssuranceBusinessDataReport(AssuranceBusinessDataReport
                                                                                        report, LoginUser loginUser) {
        Long businessId = report.getBusinessId();
        if (loginUser == null) {//事务所
            loginUser = SecurityUtils.getLoginUser();
            Long officeId = loginUser.getUser().getOfficeId();
            AntiCounterfeitingRegisteredOffice office = antiCounterfeitingRegisteredOfficeMapper.selectByOfficeId(officeId);
            report.setFirmName(office.getFirmName());
            report.setOfficeId(officeId);
            report.setCreateUser(loginUser.getUser().getUserId());
            report.setCreateBy(loginUser.getUser().getUserId().toString());
            report.setAdministrativeDivision(office.getProvince());
            report.setHasSecurities(office.getHaveSecuritiesQualification());
        }
        if (businessId == null) {
            try {
                int flag = assuranceBusinessDataReportMapper.insertReport(report);
            }catch (Exception e){
                System.out.println(e.getMessage());
            }

        } else {
            AssuranceBusinessDataReport reportE = assuranceBusinessDataReportMapper.selectReportByBusinessId(businessId);
            if (reportE != null) {
                changeAssuranceBusinessDataReportTemp(reportE);
                int status = reportE.getStatus();
                if (status == 0) {
                    log.info("保存报告数据-----------------------------------------------------------：");
                    assuranceBusinessDataReportMapper.updateReportNoCount(report);
                } else {
                    AssuranceBusinessDataReportTemp temp = new AssuranceBusinessDataReportTemp();
                    temp.setBussinessId(report.getBusinessId());
                    temp.setCreateBy(loginUser.getUser().getUserId());
                    temp.setJson(JSON.toJSONString(reportE));
                    if (report.isScipaSaveReport()) {
                        temp.setStatus(2);
                        assuranceBusinessDataReportMapper.updateReportNoCount(report);
                    } else {
                        temp.setStatus(1);
                        assuranceBusinessDataReportMapper.updateReport(report);
                    }
                    assuranceBusinessDataReportTempMapper.insertSelective(temp);

                }
            }

        }
        try {
            businessId = report.getBusinessId();
            log.info("保存报告数据，返回id-----------------------------------------------------------：" + businessId);
            // 保存签字注册师
            List<AssuranceBusinessDataRegisterSignature> assuranceBusinessDataRegisterSignatures = businessDataImportRegisterHandle(report);
            assuranceBusinessDataRegisterSignatureMapper.deleteByBusinessId(businessId);
            if (assuranceBusinessDataRegisterSignatures != null && assuranceBusinessDataRegisterSignatures.size() > 0) {
                assuranceBusinessDataRegisterSignatureMapper.batchInsertRegister(assuranceBusinessDataRegisterSignatures, businessId);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            System.out.println(e.getMessage());
        }

        return report;
    }

    /**
     * 转换注册师
     *
     * @param reportE
     */
    protected void changeAssuranceBusinessDataReportTemp(AssuranceBusinessDataReport reportE) {
        if (reportE != null) {
            List<AssuranceBusinessDataRegisterSignature> registerList = reportE.getAssuranceBusinessDataRegisterSignatures();
            if (registerList.size() > 0) {
                reportE.setSignCertificateNo1(registerList.get(0).getRegistrationCertificateNo());
                reportE.setSignerName1(registerList.get(0).getRegistrantName());
            }
            if (registerList.size() > 1) {
                reportE.setSignCertificateNo2(registerList.get(1).getRegistrationCertificateNo());
                reportE.setSignerName2(registerList.get(1).getRegistrantName());
            }
            if (registerList.size() > 2) {
                reportE.setSignCertificateNo3(registerList.get(2).getRegistrationCertificateNo());
                reportE.setSignerName3(registerList.get(2).getRegistrantName());
            }
            if (registerList.size() > 3) {
                reportE.setSignCertificateNo4(registerList.get(3).getRegistrationCertificateNo());
                reportE.setSignerName4(registerList.get(3).getRegistrantName());
            }
        }
    }

    /**
     * 生成签字注册师集合
     *
     * @param report
     */
    private List<AssuranceBusinessDataRegisterSignature> businessDataImportRegisterHandle
    (AssuranceBusinessDataReport report) {
        Long businessId = report.getBusinessId();
        List<AssuranceBusinessDataRegisterSignature> signatureList = new ArrayList<>();
        String signCertificateNo1 = report.getSignCertificateNo1();
        String signerName1 = report.getSignerName1();
        if (StringUtils.checkTowNotEmpt(signCertificateNo1, signerName1)) {
            signatureList.add(generateAssuranceBusinessDataRegisterSignature(businessId, signCertificateNo1, signerName1,report));
        }
        String signCertificateNo2 = report.getSignCertificateNo2();
        String signerName2 = report.getSignerName2();
        if (StringUtils.checkTowNotEmpt(signCertificateNo2, signerName2)) {
            signatureList.add(generateAssuranceBusinessDataRegisterSignature(businessId, signCertificateNo2, signerName2,report));
        }
        String signCertificateNo3 = report.getSignCertificateNo3();
        String signerName3 = report.getSignerName3();
        if (StringUtils.checkTowNotEmpt(signCertificateNo3, signerName3)) {
            signatureList.add(generateAssuranceBusinessDataRegisterSignature(businessId, signCertificateNo3, signerName3,report));
        }
        String signCertificateNo4 = report.getSignCertificateNo4();
        String signerName4 = report.getSignerName4();
        if (StringUtils.checkTowNotEmpt(signCertificateNo4, signerName4)) {
            signatureList.add(generateAssuranceBusinessDataRegisterSignature(businessId, signCertificateNo4, signerName4,report));
        }
        if (signatureList.size() < 1) {
            signatureList = report.getAssuranceBusinessDataRegisterSignatures();
        }
        return signatureList;
    }

    /**
     * 生成签字注册师对象
     *
     * @param businessId
     * @param signCertificateNo
     * @param signerName
     * @return
     */
    private AssuranceBusinessDataRegisterSignature generateAssuranceBusinessDataRegisterSignature(Long businessId, String signCertificateNo, String signerName,AssuranceBusinessDataReport report) {
        AssuranceBusinessDataRegisterSignature signature = new AssuranceBusinessDataRegisterSignature();
        signature.setBussinessId(businessId);
        signature.setRegistrantName(signerName);
        signature.setRegistrationCertificateNo(signCertificateNo);
        signature.setFirmName(report.getFirmName());
        signature.setOfficeId(report.getOfficeId());
        return signature;
    }

    /**
     * 报告文号重复校验
     *
     * @param reportNo
     * @return
     */
    private Integer reportNoRepeatCheck(String reportNo, Long businessId) {
        return assuranceBusinessDataReportMapper.selectCountByReportNo(reportNo, businessId);
    }

    /**
     * 报告文号重复校验
     *
     * @param reportNo
     * @return
     */
    private Integer reportNoRepeatCheck(String reportNo) {
        //20201105，wym，路径2的校验有问题，改成和路径1一样的校验
        String reportNoClean = StringUtils.removeSign(reportNo);
        List<AssuranceBusinessDataReport> assuranceBusinessDataReports = assuranceBusinessDataReportMapper.selectImport2ReportList(reportNoClean);
        if (assuranceBusinessDataReports == null) {
                return 0;
        }
        return assuranceBusinessDataReports.size();
        //return assuranceBusinessDataReportMapper.selectCountByReportNo(reportNo, null);
    }

    /**
     * 匹配审计年度、报备类型、客户名称（被审验单位名称）和客户营业执照
     * wym，这个有逻辑误区，不能简单的用or做查询条件
     * 因为数据库中“客户名称（被审验单位名称）”和“客户营业执照”是可能为空存在的
     * 如果用or查询，其中一个字段为null的话，很容易就查出结果的，导致了误判，所以判断应该换一种写法
     *
     * @param auditYear
     * @param reportType
     * @param customerName
     * @param customerBusinessLicense
     * @return =-1 参数异常
     * =0 没有匹配的项
     * >1 有匹配的项
     */
    private Integer matchConditionalData(String auditYear, String reportType, String customerName, String
            customerBusinessLicense) {
        if (StringUtils.isEmpty(auditYear) || StringUtils.isEmpty(reportType) || (StringUtils.isEmpty(customerName) && StringUtils.isEmpty(customerBusinessLicense))) {
            return -1;
        }
        return assuranceBusinessDataReportMapper.matchConditionalData(auditYear, reportType, customerName, customerBusinessLicense, null);
    }

    private Integer matchConditionalData(String auditYear, String reportType, String customerName, String
            customerBusinessLicense, Long businessId) {
        if (StringUtils.isEmpty(auditYear) || StringUtils.isEmpty(reportType) || StringUtils.isEmpty(customerName) || StringUtils.isEmpty(customerBusinessLicense)) {
            return -1;
        }
        return assuranceBusinessDataReportMapper.matchConditionalData(auditYear, reportType, customerName, customerBusinessLicense, businessId);
    }

    /**
     * 鉴证报告业务通知对应人
     *
     * @param createUser 创建人
     * @param title
     * @param content
     * @param reportId
     * @return
     */
    private int dataExceptionNotify(Long createUser, String title, String content, Long reportId) {

        return iSysNoticeService.stationLetterNotify(createUser, title, content, ProcessOptItemEnum.ASSURANCE_BUSINESS_DATA_REPORT.getItem(), reportId);
    }

    /**
     * 鉴证报告业务通知对应人
     *
     * @param title
     * @param content
     * @param reportId
     * @return
     */
    private int dataExceptionNotify(String title, String content, Long reportId) {
        return iSysNoticeService.stationLetterNotify(SecurityUtils.getLoginUser().getUser().getUserId(), title, content, ProcessOptItemEnum.ASSURANCE_BUSINESS_DATA_REPORT.getItem(), reportId);
    }
}
